LeetCode8——String to Integer (atoi)(自己编写atoi函数)
来源:互联网 发布:青年男士羽绒服知乎 编辑:程序博客网 时间:2024/05/20 13:18
题目:
参考解法:
I think we only need to handle four cases:
discards all leading whitespaces
sign of the number
overflow
invalid input
int myAtoi(char* str) { int sign = 1, base = 0, i = 0; while (str[i] == ' ') { i++; }//去掉空格 if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-');//这里i进行了++,注意符号也要输出的 }//判断符号 while (str[i] >= '0' && str[i] <= '9') { if (base > INT_MAX / 10 || ((base == INT_MAX / 10) && (str[i] - '0' > 7))) //这个条件会在加到一定程度时才触发 { if (sign == 1) return INT_MAX; else return INT_MIN; } base = 10 * base + (str[i++] - '0'); } return base * sign;}
注意这里的判断条件:
base == INT_MAX / 10 && (str[i] - '0' > 7),最后一个为什么是这个?
阅读全文
0 0
- LeetCode8——String to Integer (atoi)(自己编写atoi函数)
- LeetCode8——String to Integer (atoi)
- [LeetCode8] String to Integer (atoi)
- Leetcode8# String to Integer (atoi)
- leetcode8 String to Integer (atoi)
- leetcode8 String to Integer (atoi)
- LeetCode8:String to Integer (atoi)
- leetcode8--String to Integer (atoi)
- LeetCode8. String to Integer (atoi)
- leetcode8. String to Integer (atoi)
- leetcode8. String to Integer (atoi)
- leetcode8. String to Integer (atoi)
- leetcode8. String to Integer (atoi)
- LeetCode8. String to Integer (atoi)
- [JAVA]LeetCode8 String to Integer (atoi)
- leetcode8- String to Integer (atoi 字符串转整数)
- leetcode8. String to Integer (atoi) & 探讨补码运算溢出
- String——string-to-integer-atoi
- 深入浅出 妙用Javascript中apply、call、bind
- Ubuntu 编译安装php7时提示“freetype-config not found”
- 提高测试覆盖率
- JavaScript原型,原型链
- SQL 分析函数之KEEP (DENSE_RANK FIRST/LAST)
- LeetCode8——String to Integer (atoi)(自己编写atoi函数)
- css几行代码实现强制换行写法和强制不换行写法
- jquery css 3d旋转demo
- ASP.NET使用Jcrop插件实现图片上传裁剪功能
- Lua收到C++传入的参数类型有一种userdata
- Subline Text 3中文乱码问题解决
- 原来,坚持是这种体验
- 区块链之Hyperledgerd搭建(二、下载fabric源代码并用Docker 创建Fabric网络 & 创建/加入通道(账本))
- This page intentionally left blank.