Java Solution with pure ar manipulations


  • 0
    K

    The algorithm is based on pure division and reminder arithmetic operators. Exit condition of the loop checks remaining number if it's greater or equal to |1|. In the body of the loop we read next digit from the tail and add it to the shifted result. Each time we shift result on 1 rank multiplying it by 10 (decimal rank). In order to check overflow of 32-bit integer a reverse operation is applied to next result value. if it doesn't equal to current result then it met overflow and final result is zero.

    public int reverse(int x) {
        int r = x;
        int d, n, y = 0;
        while (r >= 1 || r <= -1) {
            d = r % 10;
            n = y * 10 + d;
            if ((n - d) / 10 == y) {
                y = n;
                r = r / 10;
            } else {
                y = 0;
                r = 0;
            }
        }
        return y;
    }
    

Log in to reply
 

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