标签:
这里面主要是考虑边界情况:
input " 1234" output 1234
input "+1234% *" output 1234
input "-1234.4" output -1234
input "%@!1234" output 0
input "2147483648" output 2147483647 正数溢出 取正数上界2147483647
input "-2147483649" output -2147483648 负数溢出 取负数下界 -2147483648
代码如下:
1 class Solution { 2 public: 3 int atoi(string str) { 4 int size = str.size(); 5 int x=0,flag=1,i=0; 6 while(str[i]==‘ ‘) 7 { 8 i++; 9 } 10 if(str[i]==‘-‘) 11 { 12 flag = -1; 13 i++; 14 } 15 else if(str[i]==‘+‘) 16 i++; 17 int j = i; 18 while(j<size) 19 { 20 if(str[j]<48 || str[j]>57) 21 { 22 size = j; 23 break; 24 } 25 j++; 26 } 27 while(i<size) 28 { 29 x = x*10 + str[i]-48; 30 i++; 31 if(flag==1&&((x==214748364&&str[i]-48>=7&&str[i]-48<=9) || (x>214748364&&i<size))) 32 return 2147483647; 33 if(flag==-1&&((x==214748364&&str[i]-48>=8&&str[i]-48<=9) || (x>214748364&&i<size))) 34 return -2147483648; 35 36 } 37 38 39 return flag*x; 40 } 41 };
标签:
原文地址:http://www.cnblogs.com/ZhangYushuang/p/4294023.html