LeetCode(5):Reverse Integer

LeetCode:Reverse Integer

Enter 123, return 321,
enter -123, return -321,
enter 120, return 21

Idea + code


1. Starting from the ones digit, calculate the number of the integer digits in turn.
2. Define the result as zero, multiply by 10 each time in the loop, and add the number of the ones digit
3.

This algorithm question, I feel that the main practice is:% and/

 public static int reverse(int x) {
        int result = 0;

        while (x !=0){
            //获得个位上的数字
            int tail=x%10;
            //结果是上次结果的10倍,加上这次算出来的尾数
            result=result*10+tail;
            //将整数除以10
            x=x/10;
        }
        return result;
    }

Guess you like

Origin blog.csdn.net/cd18333612683/article/details/79193107