zoukankan      html  css  js  c++  java
  • LeetCode

    题目

    URL:https://leetcode.com/problems/reverse-integer

    解法

    这个题目是极其简单的,对于数 x,每次对 10 取余保存为结果,之后 x 除以 10,若 x 不为0,则结果乘 10,继续取余。不过,注意一些会产生异常的条件:

    •  溢出,包括正数溢出、负数溢出;
    •  以0结尾的数字。

    有一点比较坑爹,Leetcode 并没有说异常情况的返回值,本题返回值为0。

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

    取余法,时间复杂度O(x.length),运行时间约为 36 ms

    总结

    注意细节。

    还有可能相对于乘除法而言,条件判断的代价很小。将 if 语句挪出循环体外,时间立马增加 20 ms,由原来时间领先 99% 算法变为领先 20% 算法。

  • 相关阅读:
    Nginx
    Nginx & AWStats 安装、配置、使用
    Nginx
    linux
    工作中的 Vim 和 git
    后端
    django
    django
    awk流程控制
    linux系统内置函数
  • 原文地址:https://www.cnblogs.com/Piers/p/7153045.html
Copyright © 2011-2022 走看看