7. Reverse Integer

Reverse digits of an integer.
Example1: x = 123, return 321Example2: 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.

简单的翻转每个位 这里要注意的是反正过程中很有可能是要溢出的 所以我们用了一个long 来保存 得以其值可以超过Integer.MAX_VALUE或者Integer.MIN_VALUE。 注意正溢出并不一定是负数,是否是负数完全取决于溢出后的值的最高位,如果溢出的范围够大,最高位上可能仍然是0,不能简单的与原值进行比较来排除。这与Integer.MAX_VALUE
+1的是负数是不一样的 ,后者的溢出幅度小。

class Solution {
    public int reverse(int x) {
        boolean negative = false;
        if(x==Integer.MIN_VALUE)
            return 0;
        // case overflow
        if(x<0)
        {
            x=-x;
            negative = true;
        }
        long result = 0  ;
        while(x>0)
        {
            result=result*10+(x%10);
            if(result>Integer.MAX_VALUE||result<Integer.MIN_VALUE)
                 return 0 ;
            // in case overflow shall be another way
            x=x/10;
        }
        // in what case is overflow?
         result = negative? -result:result;
            return (int)result ;
        
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容