首页 > 其他 > 详细

LeetCode: Reverse Integer 解题报告

时间:2014-12-14 09:23:35      阅读:367      评论:0      收藏:0      [点我收藏+]

Reverse Integer

Reverse digits of an integer.

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

click to show spoilers.

bubuko.com,布布扣

SOLUTION 1:

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

bubuko.com,布布扣
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

LeetCode: Reverse Integer 解题报告

原文:http://www.cnblogs.com/yuzhangcmu/p/4162196.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!