剑指offer面试题49 把字符串转换成整数 (java实现)

解题思路:

1.判断字符串输入是否合法,重点判断一个字符串除第一个字符外是否包含非数字字符,若包含,则返回0,不包含,则进行转换成整数操作;

2.取出字符串第一个字符,遍历第一个字符之后的所有字符,计算除第一个字符外的所有字符串组成的整数大小;

3.若第一个字符不是正负号,则加上第一个字符对应的数字大小。

public class Solution {

	public int StrToInt(String str) {

		if (str == null || str.length() == 0 || hasNonNumerical(str)) {
			// 如果字符串为空并且包含非数字字符
			return 0;
		}

		// 此时的字符串肯定是数字字符串
		// 因为返回值限定为int型,所以无需考虑大数问题
		char firstChar = str.charAt(0);
		// 先将除第一位的数字转换成整数
		int sumExcludeFirst = 0;
		int sum = 0;
		for (int i = 1; i < str.length(); i++) {
			// 拿出当前字符
			char c = str.charAt(i);
			// 将当前字符转换为整数
			int convert = c - '0';

			if (firstChar == '+' && sum <= Integer.MAX_VALUE) {
				sum += convert * Math.pow(10, str.length() - 1 - i);
			} 

			if (firstChar == '-' && sum >= Integer.MIN_VALUE) {
				sum -= convert * Math.pow(10, str.length() - 1 - i);
			}

			if (firstChar >= '0' && firstChar <= '9' && sum <= Integer.MAX_VALUE) {
				sum += convert * Math.pow(10, str.length() - 1 - i);
			}

		}
		

		int first = firstChar - '0';
		if (firstChar >= '0' && firstChar <= '9') {
			sum += first * Math.pow(10, str.length() - 1);
		}
		
		if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {
			return 0;
		}
		return sum;

	}

	// 判断一个字符串除第一个字符外是否包含非数字字符,第一个字符可以是+或者是—
	private boolean hasNonNumerical(String str) {

		int length = str.length();

		// 取出第0位,若第0位如果是数字或者是+,—则继续遍历,否则直接返回false
		char c = str.charAt(0);
		if ((c >= '0' && c <= '9') || (c == '+') || (c == '-')) {
			// 有必要进行之后的遍历
			for (int i = 1; i < length; i++) {
				// 取出当前字符
				c = str.charAt(i);
				if (c < '0' || c > '9') {
					// 证明包含非数字字符,直接跳出循环,返回false
					return true;
				}
			}

		} else {
			// 首位就包含除正负号外的非数字字符
			return true;
		}

		return false;
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值