Leetcode 7 Reverse Integer 倒序整數

原題目爲:java

Reverse digits of an integer.
Example1: x = 123, return 321

Example2: x = -123, return -321git

Have you thought about this? Here are some good questions to ask
before coding. Bonus points for you if you have already thought
through this!this

If the integer's last digit is 0, what should the output be? ie, cases
such as 10, 100.code

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?input

For the purpose of this problem, assume that your function returns 0
when the reversed integer overflows.it

難度: Easyio

此題讓咱們輸出給定一個整數的倒序數, 好比123倒序爲321, -123倒序爲-321. 可是若是倒序的過程當中發生整型溢出, 咱們就輸出0.ast

倒序不復雜, 關鍵在於如何斷定將要溢出.function

最終AC的程序以下:class

public class Solution {

    public int reverse(int x) {
        int x1 = Math.abs(x);
        int rev = 0;
        while (x1 > 0) {
            if (rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10) {
                return 0;
            }
            rev = rev * 10 + (x1 - (x1 / 10) * 10);
            x1 = x1 / 10;
        }
        if (x > 0) {
            return rev;
        } else {
            return -rev;
        }
    }
}

其中 x1 - (x1 / 10) * 10 是獲取x1的個位數字, 斷定下一步是否將要溢出, 使用 rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10 .

相關文章
相關標籤/搜索