leetcode之String to Integer

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.

此题的难点在于将给定String s的形式考虑全面,及溢出的问题判断。

1、将s首尾的空格删除

2、看s第一个字符是否为数字的正负符号,如果是,则记录下该符号并将该字符从s中删除

3、根据正常的数字习惯,整型数字左侧第一位要么为符号,要么为一非0的数字,所以记录好符号后, 就判断s首字符是否为0,如是,则删去,重复此步骤,直到首字符不为0;

4、准备工作做好后,就开始转换工作了。遍历s,用result记录返回结果,如s当前位置的字符不是数字,则返回result;如是,则将其存入tmp,此时要判断是否溢出。由于我们是从前往后遍历s,所以每次从s中取得一个数字时,都要将result * 10;

判断溢出的表达式是:result > (Integer.MAX_VALUE - tmp) / 10

如果不满足条件,则循环继续;直到循环结束

源代码如下:

public class StringToInteger {

	public static int atoi(String s)
	{
		s = s.trim();
		int result = 0, radix = 10;
		if(s.equals(""))
			return 0;
		char fuhao = '+';
		if(s.charAt(0) == '-')
		{
			fuhao = '-';
			s = s.substring(1);
		}else if(s.charAt(0) == '+'){
			fuhao = '+';
			s = s.substring(1);
		}
		while(s.charAt(0) == '0')
			s = s.substring(1);
		for(int i = 0; i < s.length(); ++ i )
		{
			if(Character.isDigit(s.charAt(i)))
			{
				int tmp = Character.digit(s.charAt(i), 10);
				if(result > (Integer.MAX_VALUE - tmp) / 10)
				{
					if(fuhao == '-')
						return Integer.	MIN_VALUE;
					else
						return Integer.MAX_VALUE;
				}
				result = result * radix + tmp;
			}else
				break;;
		}
		if(fuhao == '-')
			return 0 - result;
		return result;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String s = "      -11919730356x";
		System.out.println(atoi(s));
//		System.out.println(Character.digit('9', 10));
	}

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值