LeetCode: Reverse Integer 解题报告

Reverse Integer

Reverse digits of an integer.

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

click to show spoilers.

SOLUTION 1:

注意越界后返回0.先用long来计算,然后,把越界的处理掉。

public class Solution {
    public int reverse(int x) {
        long ret = 0;
        
        while (x != 0) {
            ret = ret * 10 + x % 10;
            x /= 10;
        }
        
        if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {
            return 0;
        }
        
        return (int)ret;
    }
}
View Code

 

GITHUB
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/math/Reverse.java

posted on 2014-12-14 08:25  Yu's Garden  阅读(2150)  评论(0编辑  收藏  举报

导航