[leetcode 8] String to Integer (atoi)
2014-11-08 11:34
211 查看
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.
[Solution]
注意点:
1)前缀空格
2)正负号
3)溢出 (可以使用long long int防止溢出)
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.
[Solution]
注意点:
1)前缀空格
2)正负号
3)溢出 (可以使用long long int防止溢出)
int atoi(const char *str) { long long int number = 0; int flag = 1; while ((str != NULL) && (*str == ' ')) str++; if (*str == '+') { flag = 1; str++; } else if (*str == '-') { flag = -1; str++; } while ((*str != '\0') && (*str >= '0' && *str <= '9')) { number = number * 10 + (*str - '0') * flag; if ((number < INT_MIN) || number > INT_MAX) return (flag > 0 ? INT_MAX : INT_MIN); str++; } return number; }
相关文章推荐
- leetcode 54: 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 54: 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)Dec 27 '117626 / 35090
- [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 - String to Integer (atoi)
- LeetCode: String to Integer (atoi)