leetcode 8 String to Integer (atoi) C++

来源:互联网 发布:阿里云带宽调整 编辑:程序博客网 时间:2024/06/18 16:15

需要注意的是 

前边的空格

前边的+-号,正负

中间出现了非数字则只取前边的部分

存储结果的时候不能用int,不然会越界。可以用long。


    int myAtoi(string str) {        int index = 0;        while(str[index] == ' ') index++;                int flag = 1;                if(str[index] == '+'){            index++;        }else if(str[index] == '-'){            flag = -1;            index++;        }                long result = 0;                while(index<str.size()){            if(str[index] < '0' || str[index] > '9') return flag * result;            int num = str[index++] - '0';            result = result * 10 + num;            if(flag == 1 && result > INT_MAX) return INT_MAX;            else if(flag == -1 && -result < INT_MIN) return INT_MIN;        }        return flag * result;    }


0 0