leetcode-8-字符串转数字atoi
来源:互联网 发布:淘宝金牌卖家入口 编辑:程序博客网 时间:2024/05/20 16:44
需要尽可能考虑所有的情况,不符合的情况返回0
首先字符串有可能存在前导空白,需要去掉,然后第一个字符只能为正号负号或者数字,考虑Integer的parseInt方法,如果第一个字符时正号,需要去掉。然后从第二个字符开始,一直到字符不为数字或者结束为止,使用parseInt有可能发生溢出,溢出是异常,通过判断第一个字符是否为负号来决定是返回int所能表示的最大值还是最小值。
首先去掉前导空白,使用String类的trim方法
然后判断字符串长度是否为0,为0则返回0,否则继续进行
判断第一个字符是否为正号、负号或者数字,不为这3中情况返回0,否则继续进行
使用StringBuffer保存第一个字符
从第二个数字开始判断每个字符是否为数字,为数字就使用append方法加在后面,不为数字就break
判断StringBuffer长度是否为1,为1再判断这个字符是否为数字,不为数字就返回0,为数字就使用parseInt返回int
长度不为1,判断第一个字符是否为正号,为正号就去掉第一个字符,不为正号就不做改动
使用parseInt方法返回int,如果不发生异常表示在int的表示范围之内,如果发生异常,判断第一个字符是否为负号,为负号表示负溢出,使用int的最小值,否则使用int的最大值。
public int myAtoi(String str) { str = str.trim();// 去掉前导空白和尾部空白 try { return Integer.parseInt(str); } catch (Exception e) { if (str.length() == 0) return 0; char c = str.charAt(0); if (c != '+' && c != '-' && (c - '0' < 0 || c - '0' > 9)) return 0; else { StringBuffer sbuffer = new StringBuffer(); sbuffer.append(str.charAt(0)); for (int i = 1; i < str.length(); i++) { char temp = str.charAt(i); if (temp - '0' >= 0 && temp - '0' <= 9) sbuffer.append(temp); else break; } if (sbuffer.length() == 1) { if (sbuffer.charAt(0) == '+' || sbuffer.charAt(0) == '-') return 0; else return Integer.parseInt(sbuffer.toString()); } else { if (sbuffer.charAt(0) == '+') { str = sbuffer.substring(1, sbuffer.length()); } else { str = sbuffer.toString(); } try { return Integer.parseInt(str); } catch (Exception ee) { if (str.charAt(0) == '-') return Integer.MIN_VALUE; else return Integer.MAX_VALUE; } } } } }
阅读全文
0 0
- leetcode-8-字符串转数字atoi
- LeetCode OJ 之 String to Integer (atoi字符串转数字)
- LeetCode 8. String to Integer (atoi)(字符串转数字)
- Leetcode#8. String to Integer (atoi)(字符串转数字)
- LeetCode--String to Integer (atoi)字符串转数字
- LeetCode #8 String to Integer (atoi) 字符串转数字 解题小节
- LeetCode 8 字符串转数字
- 字符串转数字atoi的重新编写及注意事项
- Leetccode String to Integer (atoi) 字符串转数字
- [LeetCode] Excel Sheet Column Number 字符串转数字
- 从字符串转数字
- js字符串转数字
- javascript 字符串转数字
- CString 字符串 转数字
- 字符串转数字
- 罗马字符串转数字
- java字符串转数字
- 字符串转数字
- ContentProvider内容提供者与ContentResolver内容访问者
- 继承
- 冒泡排序
- 算法题
- 日记day1
- leetcode-8-字符串转数字atoi
- poj3450 Corporate Identity(后缀数组+二分答案)
- 华科14_1
- git入门---30分钟学会使用git
- 蓝牙BLE LINK LAYER剖析(一) -- status and channel
- Fzu 2261 浪里个浪【思维+最短路】
- 封装
- iOS QQ中未读气泡拖拽消失的实现分析(KittenYang)
- 正向代理和反向代理