[LeetCode 解题报告]008.String to Integer (atoi)
2017-05-25 21:32
363 查看
Description:
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
accepts a
reset your code definition.
spoilers alert... click to show requirements for atoi.
注意Case点:
该字符串前边可能有若干空格(用#表示空格)“###010”返回值应为10
去除前边的若干个空格之后,需考虑接下来的一个字符是‘+‘还是’-’
碰到非数字字符结束
转换成数字时候需考虑是否产生越界
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 a
const char *argument, please click the reload button to
reset your code definition.
spoilers alert... click to show requirements for atoi.
注意Case点:
该字符串前边可能有若干空格(用#表示空格)“###010”返回值应为10
去除前边的若干个空格之后,需考虑接下来的一个字符是‘+‘还是’-’
碰到非数字字符结束
转换成数字时候需考虑是否产生越界
class Solution { public: int myAtoi(string str) { if(str.length() == 0) return 0; int i = 0, sign = 1, res = 0; while(isspace(str[i])) i ++; if(str[i] == '+' || str[i] == '-') { if(str[i] == '-') sign = 0; i ++; } str = str.substr(i); for(int j = 0; j < str.length(); j ++) { if(!isdigit(str[j])) { str = str.substr(0, j); break; } } if(str.length() == 0) return 0; for(int i = 0; i < str.length(); i ++) { int c = (str[i] - '0'); if(sign == 1 && (res > INT_MAX / 10 || res == INT_MAX / 10 && c > INT_MAX % 10)) { return INT_MAX; } else if(sign == 0 && (res > INT_MAX / 10) || res == INT_MAX / 10 && c > (INT_MAX % 10 + 1)) { return INT_MIN; } res = res * 10 + c; } return sign > 0 ? res : -res; } };
相关文章推荐
- [LeetCode] String to Integer (atoi) 解题报告
- 【LeetCode】String to Integer (atoi) 解题报告
- [Leetcode] 8. String to Integer (atoi) 解题报告
- [LeetCode] String to Integer (atoi) 解题报告
- leetcode解题报告8. String to Integer (atoi)
- 【LeetCode】String to Integer (atoi) 解题报告
- [LeetCode] String to Integer (atoi) 解题报告
- LeetCode(8) String to Integer (atoi)解题报告
- String to Integer (atoi) LeetCode 解题报告
- LeetCode-String to Integer (atoi) -解题报告
- [leetcode] 8. String to Integer (atoi) 解题报告
- LeetCode解题报告--String to Integer (atoi)
- LeetCode String to Integer (atoi) 解题报告
- LeetCode: String to Integer (atoi) 解题报告
- 【LeetCode】1. Two Sum 解题报告
- 【LeetCode】Sum of Square Numbers 解题报告
- LeetCode 2. Add Two Numbers 解题报告
- [Leetcode] 374. Guess Number Higher or Lower 解题报告
- [leetcode] 396. Rotate Function 解题报告
- [leetcode] 338. Counting Bits 解题报告