FTPrep, 8 atoi
来源:互联网 发布:51单片机时钟电路图 编辑:程序博客网 时间:2024/06/05 14:41
和上一题 reverse integer 有类似之处,但还多了几个checking的地方:
1,trim leading and trailing whitespace, just use str.trim()
2,check the 1st letter.
3,check char type must be digit, there should be a function, but it is also easy to just write <'0' or >'9'
4,overflow,both MAX_VALUE and MIN_VALUE
效率80+%
public class Solution { public int myAtoi(String str) { if(str.length()==0) return 0; String s=str.trim(); int len=s.length(); boolean isNeg=false; int i=0; if(s.charAt(i)=='-') isNeg=true; int result=0; int digit=0; if(s.charAt(i)=='-'||s.charAt(i)=='+') i++; while(i<len){ if(s.charAt(i)>'9' ||s.charAt(i)<'0' ) break; digit = s.charAt(i)-'0'; if(isNeg && -result<(Integer.MIN_VALUE+digit)/10) return Integer.MIN_VALUE; if(!isNeg && result>(Integer.MAX_VALUE-digit)/10) return Integer.MAX_VALUE; result = result*10+digit; ++i; } return isNeg?-result:result; }}
阅读全文
0 0
- FTPrep, 8 atoi
- leetcode #8 atoi
- leetcode 8 atoi
- [C++]Leetcode #8 atoi()
- atoi
- atoi
- atoi
- atoi()
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- BroadcastReceiver实现唤起已关闭应用的功能
- (Java代码实现)单链表有环的一系列问题
- Java培训第02天 Java基础知识(一)---2017年07月11日
- LIGHT OJ 1189
- 杭电1197Specialized Four-Digit Numbers
- FTPrep, 8 atoi
- Idea 配置 Tomcat服务器
- 有哪些比较安全可靠的PDF编辑器
- Linux_170712_端口
- Bmob之android支付接入
- centos下/var/empty/sshd的目录权限导致ssh远程失败
- win10你需要来自trustedinstaller的权限的解决办法
- 树莓派基础用法
- 百炼OJ:2750:鸡兔同笼