String to Integer (atoi)

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.

分析:题目输入有点恶心,各种破烂输入。唯一有点价值的就是越界的输入int的范围是-231—231-1,也就是(-2147483648--2147483647)。

当2147483647+1的时候,该数在计算机中就变成了-2147483648,也就是说这是个环,当越界的时候,就从另外一头开始,那么这是为什么呢?

因为计算机中用补码表示所有的整数,最高位是符号位,那么负数最高位的称为负权。

-2147483648 -231也就是最高位为1,其余全0。

2147483647 231-1最高位为0,其余全1。

那么-2147483648-1的计算过程如下:

class Solution {
public:
    bool isValid(char i,char next)
    {
        if(next=='-'||next=='+')
            return false;
        else
            return i=='-'||i=='+'||(i>='0'&&i<='9');
    }
    int atoi(const char *str) {
        int max=~(unsigned int)0/2;
        int min=max+1;
        if(str==NULL||str=="") return 0;
        int len=strlen(str);
        long long res=0;
        int i=0;
        while (str[i]==' ') ++i;//忽略开始的空格
if(isValid(str[i],str[i+1])){//判断符号和连续符号 switch (str[i]) { case '-': for(int q=i+1;q<len;++q){ if(str[q]>='0'&&str[q]<='9') res=res*10+str[q]-'0'; else break; } res=-res; if(res<=min) return min; return res; case '+': for(int q=i+1;q<len;++q){ if(str[q]>='0'&&str[q]<='9') res=res*10+str[q]-'0'; else break; } if(res>=max) return max; return res; default: for(int q=i;q<len;++q){ if(str[q]>='0'&&str[q]<='9') res=res*10+str[q]-'0'; else break; } if(res>=max) return max; return res; break; } } else return 0; } };

 

posted @ 2014-11-05 16:38  雄哼哼  阅读(180)  评论(0编辑  收藏  举报