LeetCode 8. String to Intrger(atoi)
来源:互联网 发布:怎么给淘宝图片加保护 编辑:程序博客网 时间:2024/06/08 15:46
问题:LeetCode 上面的问题描述一大段,总结来说就说把一个String转换成一个整数,需要考虑String中的空格和正负号,也要考虑这个数是否是一个有效的整数,最关键的是判断是否超过整数的界限,最大的整数为2147483647,最小的整数为-2147483648。
判断是否出界是最关键的,除了判断当前是否出界之外还需要判断加上下一个数之和会不会出界。
class Solution {public: int myAtoi(string str) { int i = 0; int num = 0; int tem = 0; int valid = 0; while(i < str.size() && isspace(str[i])) i++; int sign = 1; while(i < str.size() && !isdigit(str[i])) { if(i < str.size() && str[i] == '+') { valid++; i++; } else if(i < str.size() && str[i] == '-') { valid++; sign = -1; i++; } else { valid += 2; i++; } } if(valid > 1) return 0; while(i < str.size() && isdigit(str[i])) { tem = str[i] - '0'; if(num > INT_MAX / 10 || (num == INT_MAX / 10 && tem >= 8)) { return (sign == 1)? INT_MAX : INT_MIN; } num = num * 10 + tem; i++; } return sign * num; }};
阅读全文
1 0
- LeetCode 8. String to Intrger(atoi)
- [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)
- 获取url参数,分离url里面的参数
- SpringBoot的入门搭建(二)
- Spring依赖注入
- SVN快速入门
- Android 超简单音乐播放器(四)广告栏的实现
- LeetCode 8. String to Intrger(atoi)
- SpringMVC编程一般流程
- Xpath实战三:下载煎蛋网妹子照片
- Git_git 分支管理模式 git-flow lesson2 git-flow 命令
- 2016最新院基于python的pyqt开发的小麦听书项目
- SpringBoot基本配置
- Event事件
- React学习比较_初识React中的High Order Component
- 带头节点链表之插入排序(C语言版)