String to Integer (atoi)

225 篇文章 0 订阅
50 篇文章 0 订阅


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.

原网址:https://leetcode.com/problems/string-to-integer-atoi/#


看了题干里面的hint之后发现其实要考虑的情况挺多的。算法挺容易实现的,对于可能会出现的一些情况的处理写了好久。

提交的网站不断的报错,一点点的修改之前的算法。

 System.out.println( sti.myAtoi("123456789"));
 System.out.println( sti.myAtoi("123a456789"));
 System.out.println( sti.myAtoi("-123456789"));
 System.out.println("xxx");
 System.out.println( sti.myAtoi(""));
 System.out.println( sti.myAtoi("1321323213123456789"));
 System.out.println( sti.myAtoi("     010"));
 System.out.println( sti.myAtoi("    -0012a42")); 
 System.out.println( sti.myAtoi("-2147483648")); 
 System.out.println( sti.myAtoi("9223372036854775809")); 


1.为空的时候要考虑

2.负数

3.中间若出现非数字,返回之前的部分

4.空格的处理,用trim()

5.int超范围的情况,这里用到的是Long来接受,后来给的用例连Long也超了,再一想不需要。判断当前数字的位数也是可以的。int类型的范围是-2147483648~2147483647

可以通过point 这个计数来判断位数。

6.按题目要求超界限返回-2147483648或2147483647




public class Solution {
    	public int myAtoi(String str) {
		str = str.trim();
		
		if(str.length()==0)
			return 0 ;
		int len = str.length();
		// 先判断第一位
		boolean isDigit = false;
		boolean isNegative = false;
		long res = 0;

		if (str.charAt(0) >= '0' && str.charAt(0) <= '9') {
			isDigit = true;
			res = Integer.parseInt(str.charAt(0) + "");
		}
		if (str.charAt(0) == '-') {
			isDigit = true;
			isNegative = true;
		}
		if (str.charAt(0) == '+') {
			isDigit = true;
			isNegative = false;
		}
		

		if (!isDigit) {
			return 0;
		}
		// 如果后面再出现非数字也是直接结束,用long型来接受,一旦越界立即结束。 如果是负数则最后取反即可

		int point = 1;
		while (point < len && point <12) {
		    if(point>11)
			{
				if(isNegative)
					return -2147483648;
				else
					return 2147483647;
				
			}
			if (str.charAt(point) < '0' || str.charAt(point) > '9') {
				// 之前的内容如果合法就输出
				if(isNegative)
					 res=-res;
				if (res > 2147483647)
					return 2147483647;
					if(res< -2147483648)
						return -2147483648;

			
				return (int) res;
			}

			res = res * 10 + Integer.parseInt(str.charAt(point) + "");

			point++;
		}
		

		if(isNegative)
			 res=-res;
	
		if (res > 2147483647)
		return 2147483647;
		if(res< -2147483648)
			return -2147483648;
		return (int)res;
	

	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值