leetcode(2)——整数反转

leetcode第二题:整数反转

题目描述:

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

解答过程:

对于数字转换的,我习惯用字符串作操作。于是我先将整数转成字符串,对字符串做完反转操作后,再转换为整数。

class Solution {
    public int reverse(int x) {
        StringBuffer res = new StringBuffer();
        String xstr = String.valueOf(x);
        int xstrlen = xstr.length();
        char minus = '-';
        if (xstr.charAt(0) == minus) {
            res.append(minus);
            for (int i = 0; i < xstrlen - 1; i++) {
                res.append(xstr.charAt(xstrlen - 1 - i));
            }
        } else {
            for (int i = 0; i < xstrlen; i++) {
                res.append(xstr.charAt(xstrlen - 1 - i));
            }
        }
        int result = 0;
        try {
            result = Integer.valueOf(String.valueOf(res));
        } catch (NumberFormatException e) {
            result = 0;
        }
        return result;
    }
}

执行结果:通过

执行用时:3 ms, 在所有 Java 提交中击败了24.01%的用户

内存消耗:37.1 MB, 在所有 Java 提交中击败了50.88%的用户

猜你喜欢

转载自blog.csdn.net/keepfriend/article/details/107886544