1. 程式人生 > >8. String to Integer (atoi)

8. String to Integer (atoi)

pos ets 標準 rac 思路 cte present digi targe

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. spoilers alert... click to show requirements
for atoi. Requirements for atoi: The function first discards
as many whitespace characters as necessary until the first non-whitespace character is found.
Then, starting from this character,
takes an optional initial plus or minus sign followed by as many numerical digits as possible,
and interprets them as a numerical value. The string can contain additional characters after those that form the integral number,
which are ignored and have no effect on the behavior of this
function. If the first sequence of non-whitespace characters in str is not a valid integral number,
or if no such sequence exists because either str is empty or it contains only whitespace characters,
no conversion is performed. If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

這道題還是對於Integer的處理,在Reverse Integer這道題中我有提到,這種題的考察重點並不在於問題本身,而是要註意corner case的處理,整數一般有兩點,一個是正負符號問題,另一個是整數越界問題。思路比較簡單,就是先去掉多余的空格字符,然後讀符號(註意正負號都有可能,也有可能沒有符號),接下來按順序讀數字,結束條件有三種情況:(1)異常字符出現(按照C語言的標準是把異常字符起的後面全部截去,保留前面的部分作為結果);(2)數字越界(返回最接近的整數);(3)字符串結束。代碼如下:

public int myAtoi(String str) {
        
        if (str == null) {
            return 0;
        }
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        
        boolean isNeg = false;       
        int i = 0;
        if (str.charAt(0) == ‘-‘) {
            i++;
            isNeg =  !isNeg;
        } else if (str.charAt(0) == ‘+‘) {
            i++;
        }
        int ans = 0;
        while (i < str.length()) {
            if (str.charAt(i) < ‘0‘|| str.charAt(i) > ‘9‘) {
                break;
            }
            int digit =  (int)(str.charAt(i) - ‘0‘);
            if (isNeg && ans > -((Integer.MIN_VALUE + digit) / 10)) {
                return Integer.MIN_VALUE;
            }
            if (!isNeg && ans > ((Integer.MAX_VALUE - digit) / 10)) {
                return Integer.MAX_VALUE;
            }
            ans = ans * 10 + digit;
            i++;
        }
        if (ans == 0) {
            return 0;
        }else if (isNeg) {
            return -ans;
        } else {
            return ans;
        }
    }

we should pay more attention to the corner case. One is that is the result positive or negative? the other is when is the correct value out of the range of representable values?

Besides, according to the question, we should trim white space in the String, and disern the additional characters in the string.

8. String to Integer (atoi)