首页 > 编程语言 > 详细

Java for LeetCode 007 Reverse Integer

时间:2015-04-25 22:35:35      阅读:331      评论:0      收藏:0      [点我收藏+]

Reverse digits of an integer.

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

解题思路:
将数字翻转并不难,可以转成String类型翻转,也可以逐位翻转,本题涉及到的主要是边界和溢出问题,使用Long或者BigInteger即可解决。

题目不难:

JAVA实现如下:

public class Solution {
    static public int reverse(int x) {
        if(x==0||x==-2147483648)return 0;
        
        boolean isNagetive=false;
        if(x<0){
            isNagetive=true;
            x=-x;
        }
        long result=0;
        while(x!=0){
            result*=10;
            result+=x%10;
            x/=10;
        }
        final int INT_MAX=0x7fffffff;
        if((result-INT_MAX)>0)
            return 0;

        if(isNagetive)result=-result;
        return (int)result;
    }
}

 

Java for LeetCode 007 Reverse Integer

原文:http://www.cnblogs.com/tonyluis/p/4456713.html

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