String to Integer (atoi) leetcode java
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了String to Integer (atoi) leetcode java,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2356字,纯文字阅读大概需要4分钟。
内容图文
题目:
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。
越界问题?
正负号问题?
空格问题?
精度问题?
代码如下:
2 if (str == null || str.length() < 1)
3 return 0;
4
5 // trim white spaces
6 str = str.trim();
7
8 char flag = ‘+‘;
9
10 // check negative or positive
11 int i = 0;
12 if (str.charAt(0) == ‘-‘) {
13 flag = ‘-‘;
14 i++;
15 } else if (str.charAt(0) == ‘+‘) {
16 i++;
17 }
18 // use double to store result
19 double result = 0;
20
21 // calculate value
22 while (str.length() > i && str.charAt(i) >= ‘0‘ && str.charAt(i) <= ‘9‘) {
23 result = result * 10 + (str.charAt(i) - ‘0‘);
24 i++;
25 }
26
27 if (flag == ‘-‘)
28 result = -result;
29
30 // handle max and min
31 if (result > Integer.MAX_VALUE)
32 return Integer.MAX_VALUE;
33
34 if (result < Integer.MIN_VALUE)
35 return Integer.MIN_VALUE;
36
37 return (int) result;
38 }
Reference: http://www.programcreek.com/2012/12/leetcode-string-to-integer-atoi/
原文:http://www.cnblogs.com/springfor/p/3896499.html
内容总结
以上是互联网集市为您收集整理的String to Integer (atoi) leetcode java全部内容,希望文章能够帮你解决String to Integer (atoi) leetcode java所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。