leetcode第8题
来源:互联网 发布:没有网络视听许可证 编辑:程序博客网 时间:2024/04/19 17:45
8.Implement atoi to convert a string to an integer.
题目大意是实现自己的atoi函数,即将将字符串中的数字转换为int型,如果不能转换则将其转换为0,若超过整形范围。则以最大值或最小值保存。代码如下,运行时间12ms.ret保存的是结果,sign标记第一个字符是+或-,代码首先将i定位到第一个不是空格的位置,base保存了INT_MAX/10的结果,若ret>base了,则ret*10必定大于INT_MAX,若ret=base,而INT_MAX-ret*10 =7,则说明当前的字符不能大于7,否则就超过了最大整数.。
int myAtoi(string str) { int ret = 0, sign = 1; i = str.find_first_not_of(' '), base = INT_MAX / 10; if (str[i] == '+' || str[i] == '-') sign = str[i++] == '+' ?: -1; while (isdigit(str[i])) { if (ret > base || (ret == base && str[i] - '0' > 7)) return sign > 0 ? INT_MAX : INT_MIN; ret = 10 * ret + (str[i++] - '0'); } return sign * ret; }
0 0
- leetcode第8题
- leetcode 第6-8题
- LeetCode 第8题:String to Integer
- Leetcode 第189题
- leetcode第11题
- LeetCode第1题
- LeetCode第2题
- LeetCode第3题
- 第四周leetcode题
- LeetCode 第2题
- Leetcode第38题
- leetcode 第2题
- leetcode 第4题
- LeetCode第1题
- LeetCode第2题
- leetcode 第11-12题
- leetcode 第17-19题
- leetcode 第160题 MinStack
- linux下kill命令详解
- Android之屏幕适配
- c++基础(一)
- easyui 动态生成datagrid列
- ubuntu下编译contiki
- leetcode第8题
- linux下杀死进程(kill)的N种方法
- memcached 中继主从延迟数据
- java调用Properties文件
- SiteMesh页面装饰器的使用步骤
- 送给喜欢做小项目的同学的福利截止时间到年底
- 官方渠道ios应用审核加速@AppStore上架加速
- LintCode-剑指Offer-(4)丑数
- Cocos2D-x HelloWorld代码执行过程