Simple Java code - 9 lines


  • 3
    W

    Simple Java code

    public int reverse(int x) {
        int result = 0;
        while (x != 0) {
            if (result * 10 / 10 != result) return 0;   // result*10/10 will not equals result if overflow, if not overflow, result*10 + x%10 is safe, then continue
            result = result * 10 + x % 10;
            x /= 10;
        }
        return result;
    }

  • 0
    Q

    the method to check int overflow is not rigid enough


  • 0
    Q

    if result * 10=2147483646 andx %10=4,so result * 10 / 10=result,but result * 10 + x %10 is overflow.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.