标签:style blog http color os io 2014 art
解法:考虑多种情况
1 #include<cctype> 2 3 class Solution { 4 public: 5 int atoi(const char *str) { 6 int signal = 0; /*标记正负,还未出现判定正负的标志时,记为0*/ 7 long long tmp = 0; 8 9 if(*str == ‘\0‘) 10 return 0; 11 while(*str != ‘\0‘) 12 { 13 if(*str == ‘ ‘ && signal != 0) /*表明空格前以出现过数字*/ 14 { 15 break; 16 } 17 if(*str == ‘+‘) 18 { 19 if(signal == 0) /*出现正号之前没有出现过数字*/ 20 signal = 1; 21 else 22 break; 23 } 24 if(*str == ‘-‘) 25 { 26 if(signal == 0) 27 signal = -1; 28 else 29 break; 30 } 31 if(*str >= ‘0‘ && *str <= ‘9‘) 32 { 33 if(signal == 0) /*出现数字之前没出现正负号*/ 34 signal = 1; 35 tmp = tmp*10+((*str)-‘0‘); 36 } 37 if((tmp*signal)>2147483647) 38 return INT_MAX; 39 if((tmp*signal)<-2147483648) 40 return INT_MIN; 41 if((!isdigit(*str)) && (*str!=‘+‘) && (*str!=‘-‘) && (*str!=‘ ‘)) 42 { 43 break; 44 } 45 str++; 46 } 47 if(signal == 0) 48 return 0; 49 else 50 return tmp*signal; 51 } 52 };
LeetCode : string to integer (atoi),布布扣,bubuko.com
LeetCode : string to integer (atoi)
标签:style blog http color os io 2014 art
原文地址:http://www.cnblogs.com/crystal-miao/p/3877432.html