7进制字符串转为10进制的int类型数字(H3C笔试题)

【2011年华三通讯应届生笔试题】题目:请写一段将7进制转为10进制的正整数的函数。 

【思路】在Java API中有相关的函数,Integer.parsint(String str,int radix)。题目比较简单。比如,”12”,即循环进行:result=0 result=result *7+1=1; result=result*7+2=9; 本题主要考察几个异常情况和溢出情况,比如,超出Int范围如何判断。比如,某轮循环result为Integer.max/7,表明个位如果大于7进制Integer.max的个位,则溢出;某轮循环result大于Integer.max/7,则不论个位是否大于7进制Integer.max的个位,都溢出。

	private static int parseInt(String str4, int radix) {
		/* 异常情况1:字符串为null */
		if (str4 == null) {
			throw new IllegalArgumentException("字符串为null!");
		}
		int length = str4.length(), offset = 0;
		/* 异常情况2:字符串长度为0 */
		if (length == 0) {
			throw new IllegalArgumentException("字符串长度为0!");
		}
		boolean negative = str4.charAt(offset) == '-';
		if (negative) {
			throw new IllegalArgumentException("字符串位负数!");
		}
		int result = 0;
		char[] temp = str4.toCharArray();
		while (offset < length) {
			char digit = temp[offset++];
			int currentDigit = digit - '0';
			/* 一位一位判断,是否在0~7之间,否则为非法输入 */
			if (currentDigit < radix && currentDigit >= 0) {
				/* 2种溢出情况,第1种,当前的resut已经等于Integer.MAX_VALUE / 10,看个位数是否在范围内 */
				if (result == Integer.MAX_VALUE / radix
						&& currentDigit > Integer.MAX_VALUE % radix) {
					throw new IllegalArgumentException("字符串溢出!");
					/* 2种溢出情况,第2种,当前的resut已经大于Integer.MAX_VALUE / 10,不论个位是什么,都溢出 */
				} else if (result > Integer.MAX_VALUE / radix) {
					throw new IllegalArgumentException("字符串溢出!");
				}
				/*关键部分*/
				result = result * radix + currentDigit;
			} else {
				throw new IllegalArgumentException("字符串字符不在0~"+radix+"!");
			}

		}
		return result;

	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值