Q:将给出的整数x翻转。
例1:x=123,返回321
例2:x=-123,返回-321

你有思考过下面的这些问题么?
如果整数的最后一位是0,那么输出应该是什么?比如10,100
你注意到翻转后的整数可能溢出吗?假设输入是32位整数,则将翻转10000000003就会溢出,你该怎么处理这样的样例?抛出异常?这样做很好,但是如果不允许抛出异常呢?这样的话你必须重新设计函数(比如添加一个额外的参数)。

A:
用string是不是……好一点?

    public int reverse(int x) {
        String s = Integer.toString(x);
        char[] c = s.toCharArray();
        if (c[0] == '-') {
            swapIn(c, 1, c.length - 1);
        } else {
            swapIn(c, 0, c.length - 1);
        }
        String s1 = new String(c);
        int result = 0;
        try {
            result = Integer.parseInt(s1);
        } catch (Exception e) {
            return 0;
        }
        return result;
    }

    private void swapIn(char[] c, int start, int end) {
        while (start < end) {
            char temp = c[start];
            c[start] = c[end];
            c[end] = temp;
            start++;
            end--;
        }
    }

相关文章:

  • 2021-07-29
  • 2021-10-01
  • 2021-05-21
  • 2021-07-29
  • 2021-07-13
  • 2021-09-01
  • 2021-08-04
  • 2022-12-23
猜你喜欢
  • 2021-12-06
  • 2021-12-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2021-08-25
相关资源
相似解决方案