String to Integer (atoi)
来源:互联网 发布:javascript 关联数组 编辑:程序博客网 时间:2024/06/02 02:33
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 aconst char *
argument, please click the reload button to reset your code definition.
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.
Solution:
class Solution {public: int atoi(string str) { int left = 0, right = str.length() - 1; int flag = 1; long num = 0; while(str[left] == ' ') left++; while(str[right] == ' ') right--; if(str[left] == '-' || str[left] == '+') { if(str[left] == '-') flag = -1; left++; } int i = left; for(; i < str.length(); ++i) { if(str[i] >= '0' && str[i] <= '9') num = num * 10 + str[i] - '0'; else break; if(num > 2147483647) break; } if(num <= 2147483647) return num * flag; else { if(flag == -1) return -2147483648; else return 2147483647; } return 0; }};
- 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)
- 在视图中展示 rtf 域的值的方法
- 振兴中华——第四届蓝桥杯省赛C语言A组第3题
- LoadRunner的DFE功能
- 开源点评:Protocol Buffers介绍
- 编写技术分析文档的总结经验
- String to Integer (atoi)
- Thinking in java ——数组
- 使用Volley传输网络数据(官网教程)
- 吉他自学教程(一)-基础乐理
- svn server 配置 与TortoiseSVN、Ankhsvn+VS使用 及 问题
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- 最长回文子串
- 简洁代码解决PAT_1025_反转链表
- ZOJ 2319 Beatuiful People