String to Integer (atoi) | leetcode 8 【Java solving】

Implement  atoi  to convert a string to an integer.
Hint:  Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes:  It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

solution】:

We should be aware that: there may contains a sign like '+' or '-' at first. if we meet letters in string, we can break from for loop. How to handle a situation when result is far lager than Interger.MAX_VALUE.

code】:

public class Solution {
    public int myAtoi(String str) {
        str = str.trim();
        int len = str.length();
        if(len < 1) return 0;
        int flag = 1;
        int count = 0;
        double result = 0;          //the result is stored in double type so as to response to harsh test conditions.
        if(str.charAt(0) == '-' || str.charAt(0) == '+') {      //To determine whether there is a sign. if so, handle it
            if(str.charAt(0) == '-')
                flag = -1;
            count++;
        }
        for(int i=count; i<len; i++) {
            if(str.charAt(i) >= '0' && str.charAt(i) <= '9')
                result = result * 10 + str.charAt(i) - '0';
            else break;             //once meet a char is not between 0 and 9, break from "for" loop
        }
        result = flag * result;
        if(result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        if(result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        return (int)result;
    }
}
1045 / 1045  test cases passed.   Runtime: 4 ms

finally, welcome criticism!

你可能感兴趣的:(java,LeetCode,String)