Solution in Java


  • 0
    T

    In this solution, we use the fact that a long can hold larger values, so first thing we store the input into a long left. The approach is to keep dividing what's left by 10 until left is 0.

    Before we start the loop, we convert left to an absolute value so we don't need to worry about the sign of the input.

    In our loop, we:

    • Use the modulo operator to get the current least significant digit
    • Use the division operator to determine what's left.
    • Multiply the current answer by 10 and add the least significant digit.

    Next, to prevent overflow, we check that the answer isn't greater than the maximum acceptable integer value (Integer.MAX_VALUE), and if so, we change our answer to 0.

    Finally, we add the sign back to our answer and return it to the caller.

    class Solution {
        public int reverse(int x) {
            long left = x;
            long ans = 0;
            long m;
            left = Math.abs(x);
            while (left>0) {
                m = left % 10;
                left = left/10;
                ans = ans * 10 + m;
            }
            if (ans>Integer.MAX_VALUE) {
                ans = 0;
            }
            if (x != Math.abs(x)) {
                ans = 0L - ans;
            }
            return (int)ans;
        }
    }
    

Log in to reply
 

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