[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;
	}
}
虽然算法不如前几次那么奇葩,但是还是有点意思的

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值