leetcode 8 string to integer(atoi)

題目鏈接:https://leetcode.com/problems/string-to-integer-atoi/

題目的意思很是簡單:Implement atoi to convert a string to an integer, 實現函數 atoi。

如果對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.
 
  如果第一個字符是非法的,或者如果str的空的話,這個字符串的非法的。
 
  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.
 
  對於非法的字符串應該返回0, 如果有超過數據範圍的話,返回邊界值。
*/

Code:

class Solution {
public:
    int myAtoi(string str) {
        int len = str.size();
        int l = 0, r = len - 1;
        /*
         * find the left and the right of the int.
         * than count the answer.
        */
        while(str[l] == ' ') ++ l;
        if(str[l] == '+' || str[l] == '-') l ++;

        while(!(str[r] >= '0' && str[r] <= '9')) -- r;
        for(int i = l; i <= r; ++ i){
            if(!(str[i] >= '0' && str[i] <= '9')) r = i - 1;
        }
        /*
         * special for the case:
        */
        if(l > r) return 0;
        if(r - l + 1 >= 15){
            if(str[l - 1] == '-') {
                return  -2147483648;
            }
            else return 2147483647;
        }

        long long ans = 0, k = 1;
        for(int i = r; i >= l; -- i){
            ans += (str[i] - '0') * k; 
            k = k * 10;
        }

        if(l != 0 && str[l - 1] == '-') ans = -ans;
        if(ans > 2147483647) ans = 2147483647;
        if(ans < -2147483648) ans = -2147483648;

        return (int)ans;
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章