qingcheng奕  

https://oj.leetcode.com/problems/string-to-integer-atoi/

细节题,把一个字符串转换成整数

class Solution {
public:
    int atoi(const char *str) {
        if(str == NULL)
            return 0;
        
        // remove all spaces
        int i = 0;
        while(str[i] != '/0' && str[i] == ' ')
        {
            i++;
        }
        // only contain spaces
        if(str[i] == '/0')
            return 0;
        
        // 判断符号    
        bool isNegative = false;
        if(str[i] == '-')
        {
            i++;
            isNegative = true;
        }
        else if(str[i] == '+')
            i++;
        else
        { 
            // not num
            if(str[i] < '0' || str[i] > '9')
                return 0;
        }
        double ans = 0;
        while(str[i] != '/0' && str[i]>='0' && str[i] <='9')
        {
            ans = ans*10;
            ans += str[i] - '0';
            // 如果是正数
            if(isNegative == false && ans >= INT_MAX)
            {
                ans = INT_MAX;
                break;
            }
            else if(isNegative && ans >= 2147483648)
            {
                ans = INT_MIN*(-1);
                break;
            }
            i++;
        }
        
        if(isNegative)
            ans = ans *(-1);
        
        return ans;
    }
};

 

posted on 2014-08-17 14:49  qingcheng奕  阅读(120)  评论(0编辑  收藏  举报