[LeetCode][Java] String to Integer (atoi)
来源:互联网 发布:淘宝旺铺智能版功能 编辑:程序博客网 时间:2024/06/09 14:00
题目:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
题意:
实现 atoi,将字符串转化为整数。
注意考虑所有可能的情况。
算法分析:
1. 先去掉多余的空格字符,从第一个非空格字符开始。
2. 按顺序读数字,如果出现下面三种情况则结束:
2.1 异常字符出现(异常字符跳过不计)。
2.2 数字越界(返回最接近的整数)。
2.3 字符串结束
直接看代码吧,没啥难度。
AC代码:
public class Solution { public int myAtoi(String str) { int max = Integer.MAX_VALUE; int min = -Integer.MIN_VALUE; long result = 0; str = str.trim(); int len = str.length(); if (len < 1) return 0; int start = 0; boolean neg = false;//标示正负 if (str.charAt(start) == '-' || str.charAt(start) == '+') { if (str.charAt(start) == '-') neg = true; start++; } for (int i = start; i < len; i++) { char ch = str.charAt(i); if (ch < '0' || ch > '9') break; result = 10 * result + (ch - '0'); if (!neg && result > max)// 超出边界时,直接返回边界值 return max; if (neg && -result < min) return min; } if (neg) result = -result; return (int) result; }}
0 0
- [Leetcode] String to Integer (atoi) (Java)
- LeetCode – String to Integer (atoi) (Java)
- 【Leetcode】String to Integer(atoi) in JAVA
- [LeetCode Java] 8 String to Integer (atoi)
- [LeetCode][Java] String to Integer (atoi)
- [leetcode-8]String to Integer (atoi)(java)
- LeetCode : String to Integer (atoi) [java]
- Leetcode: 8. String to Integer (atoi)(JAVA)
- LeetCode(java)8. String to Integer (atoi)
- [LeetCode-Java]8. String to Integer (atoi)
- [LeetCode] 8. String to Integer (atoi) java
- leetcode String to Integer (atoi)(Java)
- String to Integer (atoi) leetcode java
- [leetcode]8. String to Integer (atoi)(Java)
- 【LeetCode】String to Integer (atoi)(java)
- LeetCode:String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- LeetCode String to Integer(atoi)
- 2015再谈游戏同步
- uva846 Steps
- OpenCV之十二 OpenCV边缘检测:Canny算子,Sobel算子,Laplace算子,Scharr滤波器合辑
- ARM-Linux交叉工具链制作
- Spring MVC 之Transaction rollback
- [LeetCode][Java] String to Integer (atoi)
- uva 10499 The Land of Justice
- android ListView,GridView 设置某一项显示位置
- OpenCV之十三 OpenCV图像金字塔:高斯金字塔、拉普拉斯金字塔与图片尺寸缩放
- 易經大意原稿(頁單位) 301-325
- 成本中心主数据屏幕增强
- 实战Memcached缓存系统(1)Memcached基础及示例程序
- 学生成绩管理系统
- uva 10790 How Many Points of Intersection?