[Leetcode]008.String to Integer (atoi)
2024-08-21 02:27:00
public class Solution {
public int myAtoi(String str) {
int index = 0, sign = 1, total = 0;
//1. 边界条件判断
if(str.length() == 0) return 0;
//2. 移除空格
while(str.charAt(index) == ' ' && index < str.length())
index ++;
//3. 处理符号位
if(str.charAt(index) == '+' || str.charAt(index) == '-'){
sign = str.charAt(index) == '+' ? 1 : -1;
index ++;
}
//4. 转变为int,并且避免溢出
while(index < str.length()){
int digit = str.charAt(index) - '0';
if(digit < 0 || digit > 9) break;
if(Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE/10 == total && Integer.MAX_VALUE %10 < digit)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
total = 10 * total + digit;
index ++;
}
return total * sign;
}
}
最新文章
- 让nodeJS支持ES6的词法----babel的安装和使用
- editplus中使用emmet?
- 《android 导入第三方源码jar包遇到的坑》
- Windows 7 安装 .netfx 4 卡住
- ZOJ 3861 - Valid Pattern Lock
- sharepoint 浏览页面导航不正确
- ruby 模块 的引入
- Spark history-server 配置 !运维人员的强大工具
- Linux 关机命令 重启命令
- css3新增的background属性
- 使用Spring Boot开发Web项目(二)之添加HTTPS支持
- Python内置函数(11)——classmethod
- (链表) leetcode 21. Merge Two Sorted Lists
- pip 安装出现超时问题的解决
- GIF录制
- Codeforces.392E.Deleting Substrings(区间DP)
- 设置macbook休眠模式
- HBase 安装设置
- 2018";百度之星";程序设计大赛 - 资格赛 1002	子串查询
- 20145234黄斐《Java程序设计》第五周