String to Integer (atoi)
来源:互联网 发布:奥地利经济学派 知乎 编辑:程序博客网 时间:2024/05/22 07:06
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.
spoilers alert... click to show requirements for atoi.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
PS:要考虑“ ”,考虑范围超出。“12a12”-->12,我一直以为是0.
class Solution {public: int atoi(string str) { string pTemp=str; int nFlag=1; bool bFlag=false; int nPos=0; while(str[nPos]==' ') { ++nPos; } if(pTemp[nPos]=='-') { nFlag=-1; bFlag=true; ++nPos; } else if(pTemp[nPos]=='+') { bFlag=true; ++nPos; } long long nResult=0; //只能long long类型 while(pTemp[nPos] !='\0') { if(pTemp[nPos]>='0' && pTemp[nPos]<='9') { nResult*=10; nResult+=pTemp[nPos]-('0'-0); if(nResult > INT_MAX) return nFlag>0 ? INT_MAX: INT_MIN; ++nPos; } else { return nResult*=nFlag; } } nResult*=nFlag; return nResult; }};
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- string to integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer(atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- SQL基础语句
- C语言学习笔记(九) -指针上 Pointer
- hnoi2014米特运输
- css float
- 关于GCD(详细)
- String to Integer (atoi)
- 虚拟光驱 DAEMON Tools Lite 安装笔记
- 触摸屏设备驱动程序
- 工频干扰现象
- 9-patch图片以及例子说明
- 数位DP的记忆化搜索形式
- 开始学习——爬取微博页面的html
- LCD设备驱动程序
- Android中View绘制流程以及invalidate()等相关方法分析 (1)