Last active
December 17, 2015 20:39
-
-
Save wfwei/5669286 to your computer and use it in GitHub Desktop.
字符串转换成整数
题目详情:
输入一个表示整数的字符串,把该字符串转换成整数并输出。例如输入字符串"345",则输出整数345。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // more smarter way to solve overflow problem | |
| int StrToInt(const char* str) | |
| { | |
| //int maxAbs=((unsigned int)~0)>>1,maxAbsDiv=maxAbs/10, maxAbsRem=maxAbs%10; | |
| int maxAbs=0x7FFFFFFF,maxAbsDiv=maxAbs/10, maxAbsRem=maxAbs%10; | |
| int val=0, i=0, sign=1; | |
| while(str[i]==' ') | |
| i++; | |
| if(str[i]=='-' || str[i]=='+'){ | |
| if(str[i]=='-'){ | |
| sign = -1; | |
| maxAbsRem ++; | |
| } | |
| i++; | |
| } | |
| while(str[i]>='0' && str[i]<='9'){ | |
| int d = str[i]-'0'; | |
| if(val>maxAbsDiv || (val==maxAbsDiv && d>maxAbsRem)){ | |
| val = maxAbs; | |
| break; | |
| }else{ | |
| val = val*10 + str[i]-'0'; | |
| } | |
| i++; | |
| } | |
| return sign>0?val:-val; | |
| } | |
| // use long to resolve overflow problem | |
| int StrToInt1(const char* str) | |
| { | |
| long long int val=0, max=1; | |
| int i=0, pos=1; | |
| while(str[i]==' ' || str[i]=='\t'){ | |
| i++; | |
| } | |
| max = (max<<31)-1; | |
| if(str[i]=='-' || str[i]=='+'){ | |
| if(str[i]=='-'){ | |
| sign = -1; | |
| max ++; | |
| } | |
| i++; | |
| } | |
| while(str[i]>='0' && str[i]<='9'){ | |
| val = val*10 + str[i]-'0'; | |
| if(val > max){ | |
| val = max; | |
| break; | |
| } | |
| i++; | |
| } | |
| return val*sign; | |
| } | |
| int main(){ | |
| printf("%d\n", StrToInt("2147483647")); | |
| printf("%d\n", StrToInt("-2147483648")); | |
| printf("%d\n", StrToInt("2147483648")); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment