LeetCode String to Integer (atoi)
来源:互联网 发布:阿里云服务器 ddos 编辑:程序博客网 时间:2024/06/14 20:02
题目:
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 ans = 0;int sign = 1;//跳过前面空格while (isspace(*str))str++;if (*str == '-')sign = -1;if (*str == '+' || *str == '-')str++;while (isdigit(*str)) {int d = *str - '0';if (INT_MAX / 10 >= ans)ans *= 10;elsereturn sign == 1 ? INT_MAX : INT_MIN;if (INT_MAX - d >= ans)ans += d;elsereturn sign == 1 ? INT_MAX : INT_MIN;str++;}return sign == 1 ? ans : -ans;}};
- 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)
- JAVA自学历程——之一(简单线程实例)
- 中文MySQL.CN如何有效更换数据库核心MariaDB
- Virtualbox 启用USB 设备支持
- CPU的快速互联通道(QPI)详解
- oracle数据库导入导出命令
- LeetCode String to Integer (atoi)
- myEclipse Debug
- QT 网络编程之udp
- 自学笔记之-指针
- oj比较分数
- 黑马程序员___接口和内部类
- 多线程并发执行的注意事项
- 好一场梦
- Oracle管道函数(Pipelined Table Function)介绍