LeetCode笔记:7. Reverse Integer

Question: (谷歌翻译)

Reverse digits of an integer.
反转数字的整数。

Example1: x = 123, return 321
Example2: x = -123, return -321

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.
如果整数的最后一位为0,那么输出应该是多少? 即例如10,100。

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
你注意到反转的整数可能会溢出吗? 假设输入是一个32位整数,则1000000003的倒数溢出。 你应该如何处理这种情况?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
出于此问题的目的,假设当反转的整数溢出时,您的函数返回0。

Note:

The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
假定输入为32位有符号整数。 当反转的整数溢出时,你的函数应该返回0。


Top Solutions:

解法1:

public int reverse(int x) {
        long rev= 0;
        while( x != 0){
            rev= rev*10 + x % 10;//从后往前反转x
            x= x/10;//去掉当前最后一位数
            if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE)
                return 0;
        }
        return (int) rev;
    }

“Very Short (7 lines) and Elegant Solution”
https://discuss.leetcode.com/topic/15134/very-short-7-lines-and-elegant-solution/2

解法2:

public int reverse(int x)
{
    int result = 0;

    while (x != 0)
    {
        int tail = x % 10;
        int newResult = result * 10 + tail;
        if ((newResult - tail) / 10 != result)//利用int溢出后得出的数值与期望值不相等的特点进行判断int是否溢出
        { return 0; }
        result = newResult;
        x = x / 10;
    }

    return result;
}

“My accepted 15 lines of code for Java”
https://discuss.leetcode.com/topic/6104/my-accepted-15-lines-of-code-for-java


My Solution:

public static int reverse(int x) {
    int result = 0;
    String input = new Integer(x).toString();
    List inputList = new ArrayList();
    List resultList = new ArrayList();

    for (int i = 0; i < input.length(); i++) {
        inputList.add(input.charAt(i));
    }
    if (inputList.contains('-')) {// 是负数
        resultList.add('-');// 输入'-'
        for (int i = input.length() - 1; i > 0; i--) {// 除去第一位的'-'号不
            resultList.add(input.charAt(i));
        }
    } else {
        for (int i = input.length() - 1; i >= 0; i--) {// 除去第一位的'-'号不
            resultList.add(input.charAt(i));
        }
    }

    //将结果转为String
    String resultString = new String();
    for (char c : resultList) {
        resultString += c;
    }

    try {//若溢出
        result = Integer.parseInt(resultString);
    } catch (NumberFormatException e) {
        return 0;
    }

    return result;
}

笔记:

Integer.MAX_VALUE:表示 int 类型能够表示的最大值。
Integer.MIN_VALUE:表示 int 类型能够表示的最小值。

你可能感兴趣的:(LeetCode,Java)