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;
        }
    }
  • 相关阅读:
    has a / is a 的区别
    Linux头文件作用
    转一篇Decorator模式的讲解文章
    歌手推荐kate st. john
    拷贝构造函数和赋值构造函数声明为私有的作用
    重新认识C++中new的用法
    系统程序员成长计划容器与算法(二)(下)
    深入C++的new
    歌手推荐Cara Dillon
    浅析一道C++设计面试题
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7512363.html
Copyright © 2011-2022 走看看