LeetCode 8. String to Integer (atoi)
来源:互联网 发布:js正则表达式实例 编辑:程序博客网 时间:2024/06/05 15:34
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.
分析:
考虑各种边界情况。
” 000123” return 123
” +000123” return 123
“-123” return -123
“123a4x” return 123
越界情况:
“2147483647” return 2147483647
“-2147483648” return -2147483648
“2147483648” return 2147483647
“-2147483649” return 2147483647
越界情况可以比较中间结果是否已经达到2147483640,即INT_MAX/10。然后再判断下一位值的情况,进而判断是否越界。
class Solution {public: int myAtoi(string str) { int result = 0; int i = 0; int sign = 1; if (str[i] != '\0') { while (str[i] == ' ') ++i; if (str[i] == '+') ++i; else if (str[i] =='-') sign = -1, ++i; while (str[i] == '0') ++i; if (str[i] != '0') { while (str[i] != '\0') { if (str[i] >= '0' && str[i] <= '9') { if (result > INT_MAX / 10) return sign == -1 ? INT_MIN : INT_MAX; // 越界情况 if (result == INT_MAX / 10) { if ((str[i] - '0' <= 7 && sign == 1) || (str[i] - '0' <= 8 && sign == -1)) { result = (result * 10) + (str[i++] - '0'); return sign * result; } return sign == -1 ? INT_MIN : INT_MAX; // 越界情况 } result = (result * 10) + (str[i++] - '0'); } else { break; } } } } return sign * result; }};
- [LeetCode]8. String to Integer (atoi)
- LeetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) Leetcode Python
- LeetCode --- 8. String to Integer (atoi)
- LeetCode 8.String to Integer (atoi)
- [Leetcode] 8. String to Integer (atoi)
- [leetcode] 8.String to Integer (atoi)
- [LeetCode] 8.String to Integer (atoi)
- <LeetCode OJ> 8. String to Integer (atoi)
- leetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) LeetCode
- leetcode 8. String to Integer (atoi)
- leetcode 8. String to Integer (atoi)
- LeetCode OJ 8.String to Integer (atoi)
- Leetcode ☞ 8. String to Integer (atoi)
- 8. String to Integer (atoi) ---Leetcode
- leetcode 8. String to Integer (atoi)
- Leetcode: 8. String to Integer (atoi)(JAVA)
- 判断一个数是否为回文数,给一个数求出是几位数,逆序输出这个数
- Notifications --- Preserving Navigation when Starting an Activity
- Nautilus启动报错
- http协议之get与post
- 2017美国数学建模ICM E题 可持续发展的城市需要(Sustainable Cities Needed!)
- LeetCode 8. String to Integer (atoi)
- 微信小程序--客服消息使用指南
- easyui treegrid 关于请求的json格式的封装处理
- The filename 未命名.ipa in the package contains an invalid character(s). The valid characters are: A-Z
- 中英文字体对照表
- CSS3 Transform
- k-means的分类数目
- opencv 记录
- 【遇见大咖】软件测试的前途与职业发展