首页 > 其他 > 详细

Leetcode第七题_Reverse Integer

时间:2015-05-14 23:50:29      阅读:273      评论:0      收藏:0      [点我收藏+]

Reverse Integer

Reverse digits of an integer.

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

这题比较容易,就是把给的一个数,反顺序输出而已。

直接对10取余数,把每一位数字读出来,再生成一个新的数就可以了,边界有一个溢出的问题,在这里,我选择的方法是定义一个long类型的变量,该变量与新生成的数赋值方法一样。然后检查这个long类型的变量是否与int类型变量的值相等就好了。

public static int reverse(int x) {
    int temp = 0;
    int res = 0;
    long testres = 0;
    while (x!=0) {
        temp = x%10;
        x = x/10;
        res = res*10 + temp;
        testres = testres*10 + temp;

    }
    if (res!=testres) {
            return 0;
        }
    return res;

}

Leetcode第七题_Reverse Integer

原文:http://blog.csdn.net/bigevil/article/details/45727711

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