String to Integer (atoi)
来源:互联网 发布:明初的疆域 知乎 编辑:程序博客网 时间:2024/04/23 19:49
题目
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.
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) { // Start typing your C/C++ solution below // DO NOT write int main() function bool flag = true; long long result = 0; for(;*str && *str==' ';str++); if(*str=='-') { flag = false; str++; } else if(*str=='+'){ str++; } while(*str) { if(isdigit(*str)) { result = 10*result + *str-'0'; if(flag && result>INT_MAX) { return INT_MAX; } if(!flag && -result<INT_MIN) { return INT_MIN; } str++; } else break ; } if(flag) return result; else return -result; }};
- 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)
- js 地址
- SecureCRT常用命令 (三)
- QTreeWidget 和QTreeWidgetItem用法总结
- wsgi初探
- IOS开源项目汇总二
- String to Integer (atoi)
- iOS和java之间的RSA加密解密、加签认证对接
- ExtJS梦想之旅(八)--GridPanel和EditorGridPanel的使用
- 能力工场--关于在JavaScript中使用EL表达式的问题
- 接口,抽象类
- 10916 - Factstone Benchmark
- Linux下启动oracle数据库
- JAVA 线程总结
- 三大WEB服务器对比分析 (apache ,lighttpd,nginx)