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

    需求

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

      注意:

      假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [Integer.MIN_VALUE,  Integer.MAX_VALUE]。请根据这个假设,如果反转后整数溢出那么就返回 0。

    示例

      输入: 123
    输出: 321
      输入: -123
      输出: -321
      输入: 120
      输出: 21

    解题

      这题我也只想到了常规的思路,每次取模,将模拼接得到结果,代码如下:

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

      但是,没有考虑到整数溢出的问题(即翻转后的整数是否在范围:Integer.MIN_VALUE<int<Integer.MAX_VALUE内),所以第二次改进:

        // 思路:将返回的结果转正long进行比较。
        public static int reverse2(int x){
            Long result = new Long(0);
            while (x != 0) {
                long mod = x % 10;
                x = x / 10;
                result = result * 10 + mod;
            }
            if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
                return 0;
            }
            return result.intValue();
        }

      想不到效果还挺好,击败百分百用户。。。。。

     

  • 相关阅读:
    程序员的基本修养之二
    jQuery学习之二
    面向对象程序的设计模式
    Mysql的复杂语句
    养成良好的做事风格
    前端模板学习bootstrap
    23. Merge k Sorted Lists
    953. Verifying an Alien Dictionary
    Daily Coding Problem: Problem #541
    396. Rotate Function
  • 原文地址:https://www.cnblogs.com/maguanyue/p/12738552.html
Copyright © 2011-2022 走看看