首页 > 其他 > 详细

Reverse Integer Leetcode

时间:2017-01-20 09:45:01      阅读:214      评论:0      收藏:0      [点我收藏+]

Reverse digits of an integer.

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

这道题要考虑反转之后overflow的问题,感觉我的写法很非主流啊。

public class Solution {
    public int reverse(int x) {
        String str = String.valueOf(x);
        StringBuilder s;
        if (x < 0) {
            s = new StringBuilder(str.substring(1, str.length()));
            s.append("-");
        } else {
            s = new StringBuilder(str);
        }
        str = s.reverse().toString();
        int newX = 0;
        try {
            newX = Integer.valueOf(str);
        } catch(Exception e) {
        }
        
        return newX;
    }
}

还是用主流写法又写了一下

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

 

Reverse Integer Leetcode

原文:http://www.cnblogs.com/aprilyang/p/6321821.html

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