zoukankan      html  css  js  c++  java
  • LeetCode——整数反转

    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--;
            }
        }
    
  • 相关阅读:
    几种排序方法详解(选择排序、冒泡排序、插入排序、快速排序)
    几种排序方法详解(选择排序、冒泡排序、插入排序、快速排序)
    Cookie
    ajax
    layer弹出框
    Session
    Cookie
    顺时针打印矩阵
    常用判断
    基础学习
  • 原文地址:https://www.cnblogs.com/xym4869/p/12652435.html
Copyright © 2011-2022 走看看