String to Integer (atoi) leetcode java
题目:
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.
spoilers alert... click to show requirements for atoi.
The function first discards as many whitespace characters as
necessary until the first non-whitespace character is found. Then,
starting from this character, takes an optional initial plus or minus
sign followed by as many numerical digits as possible, and interprets
them as a numerical value.
The string can contain additional characters after those that form
the integral number, which are ignored and have no effect on the
behavior of this function.
If the first sequence of non-whitespace characters in str is not a
valid integral number, or if no such sequence exists because either str
is empty or it contains only whitespace characters, no conversion is
performed.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values,
INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
题解:
这题主要就是考虑一下corner case。
越界问题?
正负号问题?
空格问题?
精度问题?
代码如下:
1 public int atoi(String str) {
2 if (str == null || str.length() < 1)
3 return 0;
4
5 // trim white spaces
6 str = str.trim();
7
8 char flag = '+';
9
// check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0;
// calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
i++;
}
if (flag == '-')
result = -result;
// handle max and min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) result;
}
更新:
因为遇见过了atol,string to long 这样的问题,就不能用这种比当前数据类型长的方法解决。
另一种方法是更加普遍和巧妙的,就是用这样的判断:
1. Integer.MAX_VALUE/10 < result; //当前转换结果比Integer中最大值/10还大(因为这个判断放在while循环最开始,之后还要对result进行*10+当前遍历元素的操作,所以如果还乘10的result已经比Integer.MAX_VALUE/10还大,可想而知,乘了10更大)
2. Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE%10 <(str.charAt(i) - '0') //另外的情况就是,当前result恰跟 Integer.MAX_VALUE/10相等,那么就判断当前遍历的元素值跟最大值的最后一位的大小关系即可
代码如下:
1 public int atoi(String str) {
2 if (str == null || str.length() < 1)
3 return 0;
4
5 // trim white spaces at beginning and end
6 str = str.trim();
7
8 char flag = '+';
9
// check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
int result = 0;
// calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
if(Integer.MAX_VALUE/10 < result || (Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE%10 < (str.charAt(i) - '0')))
return flag == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;
result = result * 10 + (str.charAt(i) - '0');
i++;
}
if (flag == '-')
result = -result;
return result;
}
Reference: http://www.programcreek.com/2012/12/leetcode-string-to-integer-atoi/
String to Integer (atoi) leetcode java的更多相关文章
- String to Integer (atoi) leetcode
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- String to Integer (atoi) ---- LeetCode 008
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- 8. String to Integer (atoi) ---Leetcode
Implement atoi to convert a string to an integer. 题目分析: 题目本身很简单就是将一个字符串转化成一个整数,但是由于字符串的千差万别,导致在实现的时候 ...
- LeetCode 8. 字符串转换整数 (atoi)(String to Integer (atoi))
8. 字符串转换整数 (atoi) 8. String to Integer (atoi) 题目描述 LeetCode LeetCode8. String to Integer (atoi)中等 Ja ...
- LeetCode【8】. String to Integer (atoi) --java实现
String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...
- leetcode第八题 String to Integer (atoi) (java)
String to Integer (atoi) time=272ms accepted 需考虑各种可能出现的情况 public class Solution { public int atoi( ...
- LeetCode: String to Integer (atoi) 解题报告
String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...
- leetcode day6 -- String to Integer (atoi) && Best Time to Buy and Sell Stock I II III
1. String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully con ...
- Kotlin实现LeetCode算法题之String to Integer (atoi)
题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 class ...
随机推荐
- 洛谷P3865 ST表
传送门啦 思路: $ f[i][j] $ 表示从 $ i $ 开始,包含 $ 1<<j $ 个元素的区间的区间最大值: 转移方程: $ f[i][j]=max_(f[i][j-1],f[i ...
- php 中使用include、require、include_once、require_once的区别
在PHP中,我们经常会通过include.require.include_once.require_once来引用文件,都可以达到引用文件的目的,但他们之间又有哪些区别呢,接一下我们详细的介绍一下 i ...
- java.lang.Math
四舍五人 System.out.println(Math.round(1.8f));//输出位2 static(静态)方法random() //: object/Shifting.java packa ...
- 升级 php composer 版本
在执行 composer update 时,报错 You made a reference to a non-existent script @php artisan package:discover ...
- Crack相关
Microsoft Office 2007专业增强版密钥:KXFDR-7PTMK-YKYHD-C8FWV-BBPVWM7YXX-XJ8YH-WY349-4HPR9-4JBYJCTKXX-M97FT-8 ...
- python 全栈开发,Day102(支付宝支付)
昨日内容回顾 1. django请求生命周期? - 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端 请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者po ...
- python全栈开发day17-常用模块collections,random,time,os,sys,序列化(json pickle shelve)
1.昨日内容回顾 1.正则表达式 # 正则表达式 —— str # 检测字符串是否符合要求 # 从大段的文字中找到符合要求的内容 1).元字符 #. # 匹配除换行 ...
- 练习题|python常用模块
re模块练习 1.验证手机号是否合法 import re phone_pat = re.compile('^(13\d|14[5|7]\d|15\d|166|17[3|6|7]|18\d)\d{8}$ ...
- Srorm并发机制
一:介绍 1.运行组件 2.并发度 就是executor数量 executor线程是物理线程 task是执行线程 二:增加并发度 三:Worker层次 1.worker工作进程上 各个Spout组件. ...
- [洛谷P3014][USACO11FEB]牛线Cow Line (康托展开)(数论)
如果在阅读本文之前对于康托展开没有了解的同学请戳一下这里: 简陋的博客 百度百科 题目描述 N(1<=N<=20)头牛,编号为1...N,正在与FJ玩一个疯狂的游戏.奶牛会排成一行 ...