LeetCode8. String to Integer (atoi)
Posted wilderness
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode8. String to Integer (atoi)相关的知识,希望对你有一定的参考价值。
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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
题意:把符合条件的字符串变为数字
难点:这个题不难,难在要考虑转换条件
1.连续的数字字符
2.连续的数字字符前面不能用‘+‘,’-’,之外的字符,而且加减号要和数字相接
3.连续的数字字符后面可以有字幕(不知道为什么这个可以)
4.考虑溢出
1 int myAtoi(char* str) { 2 int len,i; 3 len=strlen(str); 4 long tmp=0; 5 int flag=0; 6 for(i=0;i<len;i++) 7 { 8 while(str[i]==‘ ‘) 9 i++; 10 if(str[i]==‘+‘) 11 { 12 flag=1; 13 i++; 14 } 15 else if(str[i]==‘-‘) 16 { 17 flag=-1; 18 i++; 19 } 20 if(flag&&!(str[i]<=‘9‘&&str[i]>=‘0‘)) 21 return 0; 22 while(i<len&&(str[i]<=‘9‘&&str[i]>=‘0‘)) 23 { 24 if(tmp<0) 25 tmp=tmp*10-(str[i]-‘0‘); 26 else 27 tmp=tmp*10+(str[i]-‘0‘); 28 if(-1==flag) 29 { 30 tmp*=-1; 31 if(tmp<0) 32 flag=1; 33 } 34 if(tmp>INT_MAX) 35 return 2147483647; 36 else if(tmp<INT_MIN) 37 return -2147483648; 38 i++; 39 } 40 while(i<len) 41 i++; 42 } 43 return tmp; 44 }
以上是关于LeetCode8. String to Integer (atoi)的主要内容,如果未能解决你的问题,请参考以下文章
leetcode8.String to Integer (atoi)
LeetCode8. String to Integer (atoi)
LeetCode8. String to Integer (atoi)
leetcode8. String to Integer (atoi)