• [leetcode]_Reverse Integer


    经历了三道树的题后,完全崩溃中,急需一道非树图的题来挽救信心。

    题目:反转数字。input : 123 , output : 321.

    思路:直接,没什么好说的。

    自己代码:很龊,有大量的冗余信息,还申请了一个List,虽然AC了,但有很大改进空间。

    public int reverse(int x) {
            boolean negative = false;
            if(x < 0) {
                negative = true;
                x = x * (-1);
            }
            List<Integer> result = new ArrayList<Integer>();
            while( x / 10 > 0 ){
                result.add(x % 10);
                x = x / 10;
            }
            result.add(x);
            int num = 0;
            int times = 1;
            for(int i = result.size() - 1 ; i >= 0 ; i--){
                num += result.get(i) * times;
                times *= 10;
            }
            if(negative) return (-1)*num;
            else return num;
        }

    在网络上看了别人的代码,下面是精简版:(非常清晰,没有什么冗余开销,只用了两个变量)

    public int reverse(int x) {
            boolean negative = false;
            if(x < 0) {
                negative = true;
                x = x * (-1);
            }
            int temp = 0 ;
            while(x > 0){
                temp = temp * 10 + x % 10;
                x = x / 10;
            }
            if(!negative) return temp;
            else return (-1)*temp;
        }

    后面有个知识:负数%正数 等于负数。因此不用对负数单独进行符号判断,可以直接算。

    最优版:

    public int reverse(int x) {
            
            int temp = 0 ;
            while(x != 0){
                temp = temp * 10 + x % 10;
                x = x / 10;
            }
            return temp;
        }

    和第二个版本不同的地方在于while循环的条件由 x > 0 变为了 x != 0,这样负数也能适应该while。只使用了一个变量。五行代码。漂亮。

  • 相关阅读:
    java相关的流
    矩阵的行列式
    C语言链表逆序问题(附图解)
    RSA算法
    window.onload的用法
    linux中搜索文件内容关键字
    java.net.BindException: Address already in use: 解决方法
    设计模式之装饰者decorator模式
    java.lang.reflect.InvocationTargetException: null(已解决)
    mitmproxy 脚本启动
  • 原文地址:https://www.cnblogs.com/glamourousGirl/p/3729230.html
Copyright © 2020-2023  润新知