码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Reverse Integer 解题报告

时间:2014-12-14 09:24:32      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   java   

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 解题报告

标签:style   blog   http   io   ar   color   os   sp   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!