[LeetCode][8]String to Integer (atoi)解析与模仿Java源码实现 -Java实现
Posted 胖子程序员
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode][8]String to Integer (atoi)解析与模仿Java源码实现 -Java实现相关的知识,希望对你有一定的参考价值。
Q:
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.
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.
A:
以下解法和代码没有借阅以往任何资料,如果有更好的解法请在评论区留言
这题大概意思,就是让我们实现atoi,也就是把一个String转化成数字返回而已,在java中我们直接String.valueOf()就好了。有几个hint说要注意所有的输入的可能性。再往下看有一个Requirements for atoi:
1、可能有空格
2、正负号,而且可能有不止一个正负号
3、空值
4、超出int范围
5、没有显示内容返回0,超出范围显示INT_MAX和INT_MIN
我一看这一题我就笑了。。。不就是昨天我们说的源码吗?昨天我们使用了位运算中间就参考了以前看过的部分源码。只不过是昨天是从integer到string。今天反过来而已,不过今天这要求真够多的。
在java源码中,大致是先验证了第一个字符是不是正负号,不是的话或者只含正负号就跑异常了,然后就开始遍历呀,转化呀。重点就在转化了。我们普通转化可能用switch是吧。但是源码中可不是哟。对于-128到127之间是缓存好的数字,除此之外做了一个stirng到int的转换,在这个int转换中把char直接强转成int然后对unicode做的操作,这个就挖的太深了,我们没有必要深究了,做一些swtich转换即可。
代码如下:
public class StringtoInteger { public static void main(String[] args){ System.out.println(method(" - 94dsad564as")); } public static int method(String s){ int i = 0; int digit = 0; int result = 0; char[] cs = s.toCharArray(); int negative = 0;//0未赋值,1负值,2正值 while(i<cs.length){ if(cs[i]=='+')//正号 { if(negative != 0){ return 0; } negative = 2; }else if (cs[i]=='-') {//负号 if(negative != 0){ return 0; } negative = 1; } else if (cs[i]>=48&&cs[i]<=57) {//数字 digit = (int)cs[i]-48; result = (result<<3)+(result<<1)+digit;//*10; } i++; } return (negative==1)?-result:result; } }虽然算法不如前几次那么奇葩,但是还是有点意思的
以上是关于[LeetCode][8]String to Integer (atoi)解析与模仿Java源码实现 -Java实现的主要内容,如果未能解决你的问题,请参考以下文章
leetcode-8. String to Integer (atoi)
Leetcode 8. String to Integer (atoi)
[LeetCode] 8. String to Integer (atoi) ☆
LeetCode 8. String to Integer (atoi)