题目

String to Integer (atoi)


算法

http://www.cnblogs.com/grandyang/p/4125537.html http://blog.csdn.net/feliciafay/article/details/17111231

  • 若字符串开头是空格,则跳过所有空格,到第一个非空格字符,否则,返回0
  • 若第一个非空格是+/-号,返回0
  • 第一个不是数字返回0
  • 下一个是数字,则转化为整型,如果接下来不是数字,则返回目前结构
  • 考虑边界,超过了整型的范围,则用边界值替代当前值

代码

class Solution {  
public:  
    int myAtoi(string str) {  

        if(str.length() == 0)  
            return 0;  
        //用于存储结果  
        long long result = 0 ;  
        int sign = 1 , i=0;  

        while(i<str.length() && str[i] == ' ')
            ++i;

        if(str[i] == '+')  
            i++;  
        else if(str[i] == '-')  
        {  
            sign = -1;  
            i++;  
        }  

        for(int j=i ; j<str.length() ; j++)  
        {  
            if(str[j]>='0' && str[j]<='9')  
            {  
                result = result * 10 + (str[j]-'0');  
                if(result > INT_MAX)  
                    return sign<0 ? INT_MIN : INT_MAX;  
            }  
            else  
                break;  
        }  
        result *= sign;  
        return (int)result;  
    }  
};

results matching ""

    No results matching ""