leetcode 8 String to Integer (atoi)

没什么算法可言,但是就是要考虑周全。

1.有可能ans超过long long那么溢出以后正负可能就不对了,所以先判断超过10位的话就直接输出边值。

2.前一部分不符合规定就return 0,有这么几个情况都不行:+-2,- 992(负号和第一个数之前多了个空格,就不行)。但是+5455这种是对的。

3.5545a55这种,a及其后面的都不能算。

class Solution {
public:
    int myAtoi(string str) {
        int len=str.length();
        string st;
        int fu=2;
        for(int i=0;i<len;i++){
            if(st.length()==0&&(!(str[i]>='0'&&str[i]<='9'))){
                if(str[i]==' '&&fu==2){
                    continue;
                }
                else if(str[i]=='-'&&fu==2){
                    fu=1;
                }
                else if(str[i]=='+'&&fu==2){
                    fu=0;
                }
                else return 0;
            }
            else if(st.length()>0&&(!(str[i]>='0'&&str[i]<='9'))){
                break;
            }
            else if(str[i]>='0'&&str[i]<='9'){
                st+=str.substr(i,1);
            }
        }
        int ll=st.length();
        if(ll==0) return 0;
        long long int ans=0,shi=1;
        if(ll>10){
            if(fu==1)return -2147483648;
            else return 2147483647;
        }
        for(int i=ll-1;i>=0;i--){
            ans+=shi*(st[i]-'0');
            shi*=10;
        }
        if(fu==1) ans=-ans;
        if(ans>2147483647) return 2147483647;
        else if(ans<-2147483648) return -2147483648;
        else return (int)ans;
    }
};

 

posted @ 2015-10-26 21:51  周洋  阅读(205)  评论(0编辑  收藏  举报