标签:
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.
问题:将字符窜转换成数字
分析:感觉题目不难,但是细节很多,容易想不到
1.数字前面有空格 如s=“ 123456”
2.数字前出现了不必要或多于1个的字符导致数字认证错误,输出0 如s=“ b1234” ,s=“ ++1233” , s=“ +-1121”
3.数字中出现了不必要的字符,返回字符前的数字 如s=“ 12a12” , s=“ 123 123”
4.数字越界 超过了范围(-2147483648--2147483647) 若超过了负数的 输出-2147483648 超过了正数的输出2147483647
在科普一个知识点,倘若某个数超过了2147483647则会变为负数,反过来一样
1 class Solution { 2 public: 3 int myAtoi(string str) { 4 long long result = 0; 5 int i = 0; 6 int flag1 = 0; 7 int flag2 = 0; 8 if(str.empty()) return 0; 9 while(str[i] != ‘\0‘ && str[i] == ‘ ‘) i++; 10 while(str[i] == ‘-‘) { flag1++;i++; } 11 while(str[i] == ‘+‘) { flag2++;i++; } 12 while(i < str.length()) 13 { 14 if(str[i] >= ‘0‘ && str[i] <= ‘9‘) 15 { 16 if(flag1 > 1||flag2>1 || (flag1 == 1&&flag2 == 1)) 17 { 18 result = 0; 19 break; 20 } 21 else if(flag1 == 1) 22 { 23 result = result *10 - (str[i]-‘0‘); 24 if(result < INT_MIN) result = INT_MIN; 25 } 26 else 27 { 28 result = result *10 + (str[i]-‘0‘); 29 if(result > INT_MAX) result = INT_MAX; 30 } 31 i++; 32 } 33 else 34 { 35 break; 36 } 37 } 38 int num = (int)result; 39 return num; 40 } 41 };
(letcode)String to Integer (atoi)
标签:
原文地址:http://www.cnblogs.com/chdxiaoming/p/4726433.html