String to Integer (atoi)

51 篇文章 0 订阅
35 篇文章 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.

spoilers alert... click to show requirements for atoi.

Show Tags

Have you met this question in a real interview?


思路: 注意处理各种情况。处理顺序如下。

1. 前, 后面为空格

2. 首字母符号

3. 找到最后一位合法数字。

4. 长度是否超过10.

5. 从后往前, 每次乘10 相加

6. 注意检查超上下界。

7. 最后符号相乘。

public class Solution{
	public int atoi(String str) {
		// filter out all the whitespace characters until the first
		// non-whitespace character is found
		int start = 0;
		str = str.trim();

		// filter out the beginning 0s if it's not a 0
		start = 0;
		while (start < str.length() - 1 && str.charAt(start) == '0') {
			start++;
		}
		str = str.substring(start);

		// handle the empty string
		if (str.length() == 0) {
			return 0;
		}

		// truncate the sign
		boolean negative = false;
		if (str.charAt(0) == '-') {
			negative = true;
			str = str.substring(1);
		} else if (str.charAt(0) == '+') {
			str = str.substring(1);
		}

		// filter out all the characters after the first integral part
		int end = 0;
		while (end < str.length()) {
			char c = str.charAt(end);
			if ('0' <= c && '9' >= c) {
				end++;
			} else {
				break;
			}
		}
		str = str.substring(0, end);

		// check if the string length is too long
		if (str.length() > 10) {
			if (negative)
				return Integer.MIN_VALUE;
			else
				return Integer.MAX_VALUE;
		}

		// calculate the numeric value from the right to the left
		int ret = 0;
		int increment = 0;
		int digit = 1;
		for (int i = str.length() - 1; i >= 0; i--) {
			char c = str.charAt(i);
			increment = (str.charAt(i) - '0') * digit;
			//Check the integer range.
			if (!negative) {
				// if out of the positive integer range
				if (Integer.MAX_VALUE - ret - increment < 0) {
					return Integer.MAX_VALUE;
				}
			} else {
				// if out of the negative integer range
				if (Integer.MIN_VALUE + ret + increment > 0) {
					return Integer.MIN_VALUE;
				}
			}

			ret += increment;
			digit *= 10;
		}

		if (negative) {
			ret *= -1;
		}

		return ret;
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值