【剑指offer】之字符串转整数


题目描述:

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。


分析:

  

   这道题最主要的是要进行前面的无效判断,比如输入的是Null,输入时带有空格,输入的值有负号等。转换的过程中只要取出单一的字符减去'0'所得到的值就是该字符对应的int数值,然后循环乘以10再相加就可以得到整数。

java代码:


private static int parseString(String str) {

		if (str == null)
			throw new NumberFormatException("null");
		int result = 0;
		boolean negative = false;
		int length = str.length();
		int i = 0;
		
		while(str.charAt(i) == ' ') //去除前面的空格
			i++;
		if (length > 0) {
			if (str.charAt(i) == '-') {
				negative = true;
				i++;
			}

			for (; i < length; i++) {
				// int digit = getCharToInt(str.charAt(i));
				int digit = str.charAt(i) - '0';
				if (negative) {
					result = result * 10 - digit;
				} else {
					result = result * 10 + digit;
				}
			}
		}
		
		if(result > 0x7FFFFFFF || result < 0x80000000) { //判断是否溢出
			return 0;
		}
			
		return result;
	}

测试:

public static void main(String[] args) {
	String str = "-123";
		System.out.println(parseString(str));
	}
输出:-123


jdk中关于String转换成Int的源码,

	/**
	 * Parses the string argument as a signed integer in the radix specified by
	 * the second argument. The characters in the string must all be digits of
	 * the specified radix (as determined by whether
	 * {@link java.lang.Character#digit(char, int)} returns a nonnegative
	 * value), except that the first character may be an ASCII minus sign
	 * <code>'-'</code> (<code>'\u002D'</code>) to indicate a negative
	 * value. The resulting integer value is returned.
	 * <p>
	 * An exception of type <code>NumberFormatException</code> is thrown if any
	 * of the following situations occurs:
	 * <ul>
	 * <li>The first argument is <code>null</code> or is a string of length
	 * zero.
	 * <li>The radix is either smaller than
	 * {@link java.lang.Character#MIN_RADIX} or larger than
	 * {@link java.lang.Character#MAX_RADIX}.
	 * <li>Any character of the string is not a digit of the specified radix,
	 * except that the first character may be a minus sign <code>'-'</code> (
	 * <code>'\u002D'</code>) provided that the string is longer than length
	 * 1.
	 * <li>The value represented by the string is not a value of type
	 * <code>int</code>.
	 * </ul>
	 * <p>
	 * Examples: <blockquote>
	 * 
	 * <pre>
	 * parseInt("0", 10) returns 0
	 * parseInt("473", 10) returns 473
	 * parseInt("-0", 10) returns 0
	 * parseInt("-FF", 16) returns -255
	 * parseInt("1100110", 2) returns 102
	 * parseInt("2147483647", 10) returns 2147483647
	 * parseInt("-2147483648", 10) returns -2147483648
	 * parseInt("2147483648", 10) throws a NumberFormatException
	 * parseInt("99", 8) throws a NumberFormatException
	 * parseInt("Kona", 10) throws a NumberFormatException
	 * parseInt("Kona", 27) returns 411787
	 * </pre>
	 * 
	 * </blockquote>
	 * 
	 * @param s
	 *            the <code>String</code> containing the integer representation
	 *            to be parsed
	 * @param radix
	 *            the radix to be used while parsing <code>s</code>.
	 * @return the integer represented by the string argument in the specified
	 *         radix.
	 * @exception NumberFormatException
	 *                if the <code>String</code> does not contain a parsable
	 *                <code>int</code>.
	 */
	public static int parseInt(String s, int radix)
			throws NumberFormatException {
		if (s == null) {
			throw new NumberFormatException("null");
		}

		if (radix < Character.MIN_RADIX) {
			throw new NumberFormatException("radix " + radix
					+ " less than Character.MIN_RADIX");
		}

		if (radix > Character.MAX_RADIX) {
			throw new NumberFormatException("radix " + radix
					+ " greater than Character.MAX_RADIX");
		}

		int result = 0;
		boolean negative = false;
		int i = 0, max = s.length();
		int limit;
		int multmin;
		int digit;

		if (max > 0) {
			if (s.charAt(0) == '-') {
				negative = true;
				limit = Integer.MIN_VALUE;
				i++;
			} else {
				limit = -Integer.MAX_VALUE;
			}
			multmin = limit / radix;
			if (i < max) {
				digit = Character.digit(s.charAt(i++), radix);
				if (digit < 0) {
					throw NumberFormatException.forInputString(s);
				} else {
					result = -digit;
				}
			}
			while (i < max) {
				// Accumulating negatively avoids surprises near MAX_VALUE
				digit = Character.digit(s.charAt(i++), radix);
				if (digit < 0) {
					throw NumberFormatException.forInputString(s);
				}
				if (result < multmin) {
					throw NumberFormatException.forInputString(s);
				}
				result *= radix;
				if (result < limit + digit) {
					throw NumberFormatException.forInputString(s);
				}
				result -= digit;
			}
		} else {
			throw NumberFormatException.forInputString(s);
		}
		if (negative) {
			if (i > 1) {
				return result;
			} else { /* Only got "-" */
				throw NumberFormatException.forInputString(s);
			}
		} else {
			return -result;
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值