美文网首页
[LeetCode] 007.Reverse Integer (

[LeetCode] 007.Reverse Integer (

作者: QyQiaoo | 来源:发表于2017-08-22 01:02 被阅读0次

Problem description

Reverse digits of an integer.
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.

Code

class Solution {
    
    public int re(int x) {
        int res = 0;
        while(x != 0) {
            if((res * 10 + x % 10) / 10 != res) {
                return 0;
            }
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
    
    public int reverse(int x) {
        if(x > 0) {
            return re(x);
        } else {
            return 0 - re(0 - x);
        }
    }
}

Analysis

  • 溢出判断

相关文章

网友评论

      本文标题:[LeetCode] 007.Reverse Integer (

      本文链接:https://www.haomeiwen.com/subject/hplkdxtx.html