[Algorithm] Leetcode 7. Integer reversal (Java)

class Solution {

    public int reverse(int x) {

        long n = 0;

        while(x != 0){

            n = n*10 + x % 10;

            x = x / 10;

        }

        return (int)n ==n?(int)n:0;

    }

}

This code is a method for reversing an integer. It accepts an integer xas argument and returns its inverse result.

Inside the method, a long integer variable is first declared nand initialized to 0. Then use a loop to iterate over xeach bit of the integer. In each loop, add the current digit nto , and xdivide by 10 (dropping the last digit) to get the next digit.

After the loop ends, nconvert to an integer type and check if it is equal to the original n. If they are equal, it means that no overflow has occurred and type conversion can be performed safely; otherwise, it means that overflow has occurred and the result needs to be set to 0. Finally, the reversed result is returned.

To sum up, the function of this code is to reverse the input integer xand return the reversed integer value.

  public int reverse(int x) {
        long n = 0;
        while(x != 0) {
            n = n*10 + x%10;
            x = x/10;
        }
        return (int)n==n? (int)n:0;
    }

Attached is the  link of the boss

Guess you like

Origin blog.csdn.net/Feixiangdechenyu/article/details/131841657