美文网首页
4. String 转换成 int

4. String 转换成 int

作者: 月巴月巴 | 来源:发表于2018-07-21 13:12 被阅读0次

这道题之前面甲骨文的时候被问过。当时是不要求判断正负号的。
一般被问到什么问题,还是看心情。自己面别人也一样。所以不要迷信题库。

这里写的是可以转换正数和负数的。
如果数字中间有空格,则只转换空格之前的部分。
会判断无效的输入(非数字).

需要注意的几点:

  1. char的 ‘0’, ‘1’, ‘2’, ‘3’字符如何转换成对应的数字
    char - '0'
  2. 对于Max, Min的判断, 这里只说Max的,Min的在代码里,思路差不多
    如果 result 在 计算下一位的时候已经比Max的1/10要大,则说明输入值已经超出范围。
    如果result 在 计算下一位的时候与Max的1/10一样大,则看下一个加入的数字是否不大于Max的最后一位。
/**
 * Created by creat on 2018/7/19.
 * If there is space in the Integer, return the first part
 * Can print and validate both Positive and Negative numbers
 * Get the result in One loop. startOfInput -> startPosition, startPosition -> endOfValidInput
 */
public class StringToInteger {
    int IN_VALID_NUMBER_CODE = -1;
    char SPACE = ' ';
    int TENTH_OF_MAX_INT = Integer.MAX_VALUE / 10;
    int LAST_DIGIT_OF_MAX_INT = Integer.MAX_VALUE % 10;
    int TENTH_OF_MIN_INT = Integer.MIN_VALUE / 10;
    int LAST_DIGIT_OF_MIN_INT = 0 - Integer.MIN_VALUE % 10;

    public static void main(String[] args) {
        StringToInteger sti = new StringToInteger();
        System.out.println("Max Int = " + Integer.MAX_VALUE + "  And Min Int = " + Integer.MIN_VALUE);

        System.out.println(sti.convertStringToInteger("1234")); // happy path positive
        System.out.println(sti.convertStringToInteger("-1")); // happy path negative
        System.out.println(sti.convertStringToInteger("2147483647")); //  happy path max int
        System.out.println(sti.convertStringToInteger("+2147483647")); //  happy path max int with sign
        System.out.println(sti.convertStringToInteger("-2147483648")); //  happy path min int
        System.out.println(sti.convertStringToInteger("2147483648")); // too big
        System.out.println(sti.convertStringToInteger("-2147483649")); // too small
        System.out.println(sti.convertStringToInteger("    +2147483647  ")); //  happy path max int and space
        System.out.println(sti.convertStringToInteger("    -2147483648  ")); //  happy path min int and space
        System.out.println(sti.convertStringToInteger("    -214 7483648  ")); //  happy path min int and space, take the valid part before space

        // below are invalid input tests
        System.out.println("***************** Below are Invalid Input tests***************");
        System.out.println(sti.convertStringToInteger("ab123cd"));
        System.out.println(sti.convertStringToInteger("+0123"));
        System.out.println(sti.convertStringToInteger("-0123"));
        System.out.println(sti.convertStringToInteger("-123abc123"));

    }

    public int convertStringToInteger(String str) {
        if (str == null || str.isEmpty()) {
            System.out.println("No Input");
            return IN_VALID_NUMBER_CODE;
        }
        int result = 0;
        int beginPosition = -1;
        int firstNumberPosition = -1;
        char[] contents = str.toCharArray();

        for (int i = 0; i < contents.length; i++) {
            if (contents[i] == SPACE) {
                continue;
            }
            if (isSign(contents[i]) || isDigit(contents[i])) {
                beginPosition = i;
                break;
            }

        }

        if (beginPosition == IN_VALID_NUMBER_CODE) {
            System.out.print("Invalid Input");
            return IN_VALID_NUMBER_CODE;
        }

        if (isSign(contents[beginPosition])) {
            firstNumberPosition = beginPosition + 1;
        } else {
            firstNumberPosition = beginPosition;
        }

        if (contents[firstNumberPosition] == '0') {
            System.out.print("Invalid Input");
            return IN_VALID_NUMBER_CODE;
        }

        for (int j = firstNumberPosition; j < contents.length; j++) {
            if (contents[j] == SPACE) {
                return result;
            }
            int digit = getDigit(contents[j]);
            if (digit == IN_VALID_NUMBER_CODE) {
                System.out.print("Invalid Input");
                return IN_VALID_NUMBER_CODE;
            }
            if (isPositive(contents[beginPosition]) && result > TENTH_OF_MAX_INT) {
                System.out.print("The input number is too large");
                return IN_VALID_NUMBER_CODE;
            }
            if (isPositive(contents[beginPosition]) && result == TENTH_OF_MAX_INT && digit > LAST_DIGIT_OF_MAX_INT) {
                System.out.print("The input number is too large");
                return IN_VALID_NUMBER_CODE;
            }

            if (!isPositive(contents[beginPosition]) && result > 0 - TENTH_OF_MIN_INT) {
                System.out.print("The input number is too small");
                return IN_VALID_NUMBER_CODE;
            }
            if (!isPositive(contents[beginPosition]) && result == 0 - TENTH_OF_MIN_INT && digit > LAST_DIGIT_OF_MIN_INT) {
                System.out.print("The input number is too small");
                return IN_VALID_NUMBER_CODE;
            }


            result *= 10;
            result += digit;
        }
        return isPositive(contents[beginPosition]) ? result : 0 - result;
    }

    private boolean isPositive(char c) {
        return c == '+' || isDigit(c);
    }

    private int getDigit(char c) {
        if (isDigit(c)) {
            return c - '0';
        } else {
            return IN_VALID_NUMBER_CODE;
        }
    }

    private boolean isDigit (char c) {
        return c >= '0' && c <= '9';

    }

    private boolean isSign(char c) {
        return c == '+' || c == '-';
    }
}

相关文章

网友评论

      本文标题:4. String 转换成 int

      本文链接:https://www.haomeiwen.com/subject/bslhmftx.html