8. String to Integer (atoi)
来源:互联网 发布:手机音乐可视化软件 编辑:程序博客网 时间:2024/05/29 19:24
public class Solution { public int myAtoi(String str) { Boolean negativeFlag = false; Boolean positiveFlag = false; int st = 0; long ans = 0; long max = 2147483648L; if(str.equals("")){ return 0; } while(st < str.length() && str.charAt(st) == ' '){ st ++; } if(st < str.length() && str.charAt(st) == '+') { st++; positiveFlag = true; }else{ if(st < str.length() && str.charAt(st) == '-'){ st ++; negativeFlag = true; } } if(negativeFlag == true && positiveFlag == true){ return 0; }else{ for(int i = st;i < str.length(); i++){ if(str.charAt(i) <= '9' && str.charAt(i) >= '0'){ ans = ans * 10 + str.charAt(i) - '0'; if(ans > max){ ans = (int)max; if(negativeFlag) return Integer.MIN_VALUE; if(positiveFlag || (negativeFlag ==false && positiveFlag == false)) return Integer.MAX_VALUE; break; } } else break; } } if(negativeFlag) ans = -ans; if(ans >= Integer.MAX_VALUE) ans = Integer.MAX_VALUE; if(ans <= Integer.MIN_VALUE) ans = Integer.MIN_VALUE; return (int)ans; }}
注意考虑 + - 空格 无效字符 除正负号外,大于2147483647的数,比如“-2147483648”,除符号“-”外,“2147483648”是大于int的最大值2147483647的,故返回应该是 -2147483648
阅读全文
0 0
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 机器学习第三周(一)--逻辑回归引入
- 个人java学习回顾01
- dubbo源码深度解读三之container模块
- 面试---算法排序(3)(希尔排序)
- js 之 prototype原型 理解
- 8. String to Integer (atoi)
- word转pdf
- 华为机试——坐标移动
- beego框架介绍
- 9点C++(5)
- 几种排序算法的思想
- git stash和git stash pop
- 理解OAuth 2.0
- activemq