• [Leetcode] reverse integer 反转整数


    Reverse digits of an integer.

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

    click to show spoilers.

    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?

    Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

    题意:将一个整数反转。

    思路:这题有几个要注意的地方:一、正负号;二、反转后的结果是否溢出。第二点很重要,关于这点题目中有详细的说明。这里有两种解法方法:

    方法一:改变返回结果的变量类型为long long ,这样,若是最终计算的结果超过INT_MAX,就返回0;否则,结构符号输出即可。

    代码如下:

     1 class Solution {
     2 public:
     3     int reverse(int x) 
     4     {
     5         long long  res=0;
     6         int cur=abs(x);
     7 
     8         while(cur>0)
     9         {
    10             res=res*10+cur%10;
    11             cur/=10;
    12         }    
    13         if(res>INT_MAX) return 0;
    14         return x>=0?res:-res;   
    15     }
    16 };

    方法二:不用改变返回的变量类型,在while循环中,在计算res之前,若res>INT_MAX/10,就返回0,因为若是大于,则后续的计算中乘以10 了,还是会大于,所以提前返回。代码如下:

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

    在LeetCode上测试时,第二种方法,明显好些。

  • 相关阅读:
    003 python接口 cookies
    RocketDock 安装
    001 python接口 get请求
    mysql创建远程登陆用户并授权
    php时间函数
    ThinkPHP5高阶实战教程
    unset与unlink
    include 和require的区别
    80端口被system 占用
    【纪中受难记】——C2Day4:水题大赏
  • 原文地址:https://www.cnblogs.com/love-yh/p/7199217.html
Copyright © 2020-2023  润新知