7. Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

分析

注意读入和返回的数都是 int 型的,这时就要考虑反转后这个数会不会超 int,超的话就返回 0 。这时处理数时最好用比 int 大的类型,不然恐怕会超范围。

public class Solution {  
  
    public int reverse(int x) {  
        int ret = 0;  
        while (Math.abs(x) != 0) {  
            if (Math.abs(ret) > Integer.MAX_VALUE)  
                return 0;  
            ret = ret * 10 + x % 10;  
            x /= 10;  
        }  
        return ret;  
    }  
}  
原文地址:https://www.cnblogs.com/zxqstrong/p/5274613.html