zoukankan      html  css  js  c++  java
  • 【Leetcode】【Easy】Reverse Integer

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321

    Have you thought about this?

    Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

    If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

    Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    注意:

    此题在2014年11月10日前,对结果没有加入整数溢出的测试。加上后,下面代码存在Bug(1027 / 1032 test cases passed)。

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4        int res = 0;
     5        
     6        while (x) {
     7            res = 10 * res + x % 10;
     8            x /= 10;
     9        }
    10        
    11        return res;
    12     }
    13 }; 

    原因:int占用4个字节,能表示的范围是:-2,147,483,648 ~ 2,147,483,647。当反转时会遇到“10 * res”的过程,也就是此整数正着可能不越界,但是倒过来就会越界。

    解题思路1:

    在“10 * res”前加上判定语句,防止越界。

    注意:

    1、对2^31/10进行判定,不要对2^31进行判定,也就是不要和准确的边界值比大小。因为当整数已经越界时,它的值自动变化,再拿它比较永远不会越界;

    2、注意多个&& || 混合时的优先级问题;

    AC代码:

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         int res = 0;
     5        
     6         while (x) {
     7             if ((res < INT_MIN/10) || (res > INT_MAX/10)) {
     8                 res = 0;
     9                 break;
    10             }
    11             
    12             res = 10 * res + x % 10;
    13             x /= 10;
    14         }
    15        
    16         return res;
    17     }
    18 };

    解题思路2:

    直接声明res为long(未适应32位和64位,应该是long long),这样就不会在计算中对long越界,返回结果时再判断是否对int越界;

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         long res = 0;
     5        
     6         while (x) {
     7             res = 10 * res + x % 10;
     8             x /= 10;
     9         }
    10         
    11         if ((res>INT_MAX) || (res < INT_MIN))
    12             res = 0;
    13         
    14         return res;
    15     }
    16 };
  • 相关阅读:
    世界上最受欢迎的色彩出炉了,她的名字叫马尔斯绿
    一步一步学会preload和prefetch
    chrome插件编写中需要了解的几个概念和一些方法
    SVG矢量绘图 path路径详解(贝塞尔曲线及平滑)
    为什么Object.prototype在Function的原型链上与Function.prototype在Object的原型链上都为true
    排序算法总结
    iterm2 "agnoster"主题设置中的一些踩坑 2018.8
    webpack4与babel配合使es6代码可运行于低版本浏览器
    认识JWT
    「前端进阶」彻底弄懂前端路由
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4186051.html
Copyright © 2011-2022 走看看