Skip to content

Latest commit

 

History

History
92 lines (82 loc) · 2.88 KB

把字符串转化成整数.md

File metadata and controls

92 lines (82 loc) · 2.88 KB

题目描述

将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

测试用例

  • 功能测试(输入的字符串表示整数、负数和0)
  • 边界值测试(最大的正整数;最小的负整数)
  • 特殊输入测试(输入的字符串为空指针;输入的字符串为空字符串;输入的字符串中有非数字字符等)

题目考点

  • 考察应聘者的沟通能力,毕竟有很多细节处理。
  • 考察应聘者思维的全面性。

解题思路

参照Integer.valueOf(string)方法

这道题虽然简单,但是很容易写出不全面的代码,这时候就需要考虑测试用例了,主要解决如下问题:

  1. 空指针、空串
  2. 整数溢出
  3. 非法字符
  4. 首字符为+、-

自己解题

很不全面

参考解题

/**
 * 把字符串转换成整数
 *
 * @Author rex
 * 2018/9/19
 */
public class Solution {
    /**
     * 把字符串转换成整数
     *
     * @param str
     * @return
     */
    public int strToInt(String str) {
        // 表示10进制转换
        int radix = 10;

        // 防止特殊输入
        if (str == null) {
            throw new NumberFormatException("null");
        }
        // 定义返回值
        int result = 0;
        // 正负数标志位
        boolean negative = false;

        int i = 0, len = str.length();

        if (len > 0) {
            // 处理首字符为+、-号的情况
            // 取出第一个字符判断是否为+、-
            char firstChar = str.charAt(0);
            // + 、 - 的ASCII码都比0小
            if (firstChar < '0') {
                if (firstChar == '-') {
                    negative = true;
                } else if (firstChar != '+') {
                    throw new NumberFormatException("invalid first char");
                }
                if (len == 1) {
                    throw new NumberFormatException("invalid string");
                }
                i++;
            }

            while (i < len) {
                if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                    result = result * radix + str.charAt(i) - '0';
                    // 处理数字溢出
                    if ((!negative && result > Integer.MAX_VALUE) || (negative && result < Integer.MIN_VALUE)) {
                        throw new NumberFormatException("invalid string");
                    }
                    // 处理非法字符
                } else {
                    throw new NumberFormatException("invalid char");
                }
                i++;
            }
            // 处理空串
        } else {
            throw new NumberFormatException("invalid string");
        }
        return negative ? -result : result;
    }
}