zoukankan      html  css  js  c++  java
  • [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上测试时,第二种方法,明显好些。

  • 相关阅读:
    bzoj4513: [Sdoi2016]储能表
    bzoj4000: [TJOI2015]棋盘
    bzoj3067: Hyperdrome
    bzoj4943: [Noi2017]蚯蚓
    bzoj4044: [Cerc2014] Virus synthesis
    bzoj3676: [Apio2014]回文串
    bzoj4543: [POI2014]Hotel加强版
    bzoj1921: [Ctsc2010]珠宝商
    bzoj4754: [Jsoi2016]独特的树叶
    作图的配色
  • 原文地址:https://www.cnblogs.com/love-yh/p/7199217.html
Copyright © 2011-2022 走看看