Reverse digits of an integer.

来源:互联网 发布:知乎洛基香港代购苹果 编辑:程序博客网 时间:2024/06/04 23:33

Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

class Solution {    public int reverse(int x) {        int result=0;        while(x!=0){            int tail=x%10;            result=result*10+tail;            if((result-tail)%10!=0)//判断是否溢出                return 0;            x=x/10;        }//若x!=0都可以用此种方法得到翻转的的值        return result;        //若x=0,则返回0.    }}

注意:最重要的是循环判断条件的设置和溢出的判断。