LeetCode | String to Integer (atoi)
来源:互联网 发布:淘宝大图轮播尺寸 编辑:程序博客网 时间:2024/06/06 03:42
题目:
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) { while(*str!='\0'&&*str==' ') { str++; }; if(*str=='\0') { return 0; } else { bool positive=true; if(*str=='-') { positive=false; str++; } else if(*str=='+') { str++; } int result=0; while(*str!='\0') { if(*str>='0'&&*str<='9') { if(result>=(INT_MAX-(*str-'0'))/10+((INT_MAX-(*str-'0'))%10==0?0:1)) { result = INT_MAX; } else if(result<=(INT_MIN+(*str-'0'))/10+((INT_MIN+(*str-'0'))%10==0?0:-1)) { result = INT_MIN; } if(result!=INT_MAX&&result!=INT_MIN) { result = result*10+(*str-'0')*(positive?1:-1); } } else { break; } str++; } return result; } }};
- LeetCode:String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- LeetCode String to Integer(atoi)
- LeetCode :String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- Leetcode : String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- LeetCode-String to Integer (atoi)
- [leetcode] String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- [LeetCode] String to Integer (atoi)
- leetcode String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- 文本特征提取方法研究
- NDK开发环境搭建_r8
- 在Windows Azure上基于CentOS 6.3部署MySQL 5.6主从式数据库(1)
- 二叉树的最近父结点的查找(Least Common Ancestor)
- Linux基础.控制台式查看日志
- LeetCode | String to Integer (atoi)
- linux下tar.gz、tar、bz2、zip等解压缩、压缩命令小结
- toj2194Mine(dfs)
- 算法导论 5.1-3
- java提高篇(十四)-----关键字final
- Linux 下压缩与解压.zip和.rar及.7z文件
- 变换不变性
- Html5初学_____(2)
- 消息队列、AMQP和RabbitMQ