zoukankan      html  css  js  c++  java
  • lintcode413- Reverse Integer- easy

    Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).

    Example

    Given x = 123, return 321

    Given x = -123, return -321

    关键在怎么判断出overflow

    法1:存好旧的old,接着先加了得new,看new/10是否与old吻合,不一样就出问题了。

    法2:加下一个数字前,把当前数字 vs max/10与min/10,超了就出问题了。

    细节:

    1.法2不用判断正好等于的情况,因为最大数是2xxxxxxxx7(8),而唯一会溢出的就是输入int digit位满了可能反过来才会有问题,但这种情况下输入必定第一位是1或者2。如果当前是等于情况,加上1/2不会超过最后的7/8。
    2.法2最大值表示可以是Integer.MAX_VALUE,或者就临时写int max = 0x7FFFFFFF; int min = 0x80000000;
    3.数字倒过来循环里写的是res = res * 10 + digit;很简单的表达方式,请写熟练。 
     
    实现:
    法1
    public class Solution {
        /*
         * @param n: the integer to be reversed
         * @return: the reversed integer
         */
        public int reverseInteger(int n) {
            // write your code here
            int res = 0;
            while (n != 0){
                int digit = n % 10;
                int temp = res * 10 + digit;
                if (temp / 10 != res){
                    return 0;
                }
                res = temp;
                n /= 10;
            }
            return res;
        }
    }
    法2
    public class Solution {
        /*
         * @param n: the integer to be reversed
         * @return: the reversed integer
         */
        public int reverseInteger(int n) {
            // write your code here
            int max = 0x7FFFFFFF;
            int min = 0x80000000;
            int res = 0;
            while (n != 0){
                int digit = n % 10;
                if (res > max / 10 || res < min / 10){
                    return 0;
                }
                res = res * 10 + digit;
                n /= 10;
            }
            return res;
        }
    }
  • 相关阅读:
    JS中的继承(上)
    一篇文章理解JS继承——原型链/构造函数/组合/原型式/寄生式/寄生组合/Class extends
    JS 装饰器,一篇就够
    理解 JavaScript 的 async/await
    JS正则表达式入门,看这篇就够了
    JavaScript的几种循环方式
    全解跨域请求处理办法
    下班后的时间精力生活管理办法(时间管理)
    hexo上部署博客到Github失败
    11
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7512363.html
Copyright © 2011-2022 走看看