String to Integer (atoi)
来源:互联网 发布:维也纳攻略 知乎 编辑:程序博客网 时间:2024/06/05 09:21
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.
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.
class Solution {public: int atoi(const char *str) { int sign=1; long long ans=0; if(*str=='\0') return 0; while(*str==' ') str++; if(*str=='-'){ sign=-1; str++; } else{ if(*str=='+') str++; } while(*str!='\0'){ if(*str>='0' && *str<='9'){ ans=ans*10+int(*str-'0'); if(ans*sign>INT_MAX){ ans=INT_MAX; break; } else{ if(ans*sign<INT_MIN){ ans=INT_MIN; sign=1; break; } } str++; } else break; } ans=ans*sign; return ans; }};
- 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)
- 转砖桩浊坐庄缀椎篆桩驻撰准琢籽姿佐租
- 分布式与集群的区别
- android开发之URL传参的问题
- 安卓中dp和实际位图的px的转换
- 工作总结--秦浩
- String to Integer (atoi)
- Windows锁定计算机C代码编程实现
- UVA_624 CD
- 2015-2-8工作日志-张吉林
- poj 1006 Biorhythms
- Android中的自动朗读(TTS)
- 云开发环境 IDE
- 二分第二弹
- 【转载】serialVersionUID有什么作用