LeetCode题解--7. Reverse Integer

链接


7.Reverse_Integer (Easy)

题目:https://leetcode.com/problems/Reverse-Integer/

代码(github):https://github.com/gatieme/LeetCode/tree/master/007-ReverseInteger

CSDN题解;http://blog.csdn.net/gatieme/article/details/51045626

题意


反转一个数。

Reverse digits of an integer.

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

分析


很明显,简单题,反转我们很容易写出下面的代码

while (x)
{
  res = res * 10 + x % 10; // 加号前面是先取得的值保持最高位, 后面则是取得原数的个位.
  x /= 10; // 裁剪原数, 确保能够从低位到高位的值, 能够被依次取得.
}

简单题目,我们就要看看有没有陷阱了?

overflow问题


如果给出了一个超过int表示范围的数,比如1534236469,会发生什么

LeetCode题解--7. Reverse Integer_第1张图片

这个怎么处理呢,

为了保证能准确补货溢出,将 res 设为 long, 那你一个 int 怎么反转都不会超出 long 的范围了吧?

然后判断 res 和 INT_MAX的关系就可以了.

INT_MAX宏(定义C库头文件在limits.h)

如果溢出返回0

res > INT_MAX ? 0 : res;                                        

负数的问题


负数这个也要注意,有两种解决办法,

  • 一种方法是开始时候就判断正负,把所有的数更正为正数的情况进行处理。然后在返回时,再按照原类型返回。

  • 返回时,注意正负的问题

LeetCode题解--7. Reverse Integer_第2张图片

fabs(res) > INT_MAX ? 0 : res;                                        

后导0的问题


这个问题我们的算法已经规避了

代码



/*题意:
 *
 * 反转一个数。
 *
 * 分析:
 *
 * ==1==  overflow的问题?
 *
 * 注意读入和返回的数都是 int 型的,
 *
 * 这时就要考虑反转后这个数会不会超 int,超的话就返回 0 。
 *
 * 检测很简单, 将 res 设为 long, 那你一个 int 怎么反转都不会超出 long 的范围了吧? 然后判断 res 和 INT_MAX的关系就可以了.
 *
 * 这时处理数时最好用比 int 大的类型,不然恐怕会超范围。
 *
 * 当然也可以用 int :if (result > (INT_MAX/10))
 *
 * ==2==还有一点就是还要考虑前导零。
 *
 * 后几位是0的情况(10, 100.)?
 *
 * */


#include 
#include 


#include      // use `INT_MAX`
#include        //  use `fabs`

#define  DEBUG

int reverse(int num)
{
    long res = 0;
    while(num != 0)
    {
        res =  res * 10 + num % 10;

        num /= 10;
    }
    return fabs(res) > INT_MAX ? 0 : res;

}


#ifdef DEBUG
int main()
{
    printf("reverse(%d) = %d\n", 123, reverse(123));
    printf("reverse(%d) = %d\n", -123, reverse(-123));              //  use x != 0
    printf("reverse(%ld) = %d\n", 1534236469, reverse(1534236469));  //
    printf("reverse(%d) = %d\n", 1234000, reverse(1234000));
    printf("reverse(%ld) = %d\n", -2147483648, reverse(-2147483648));

    return EXIT_SUCCESS;
}

#endif

你可能感兴趣的:(┈┈【LeetCode,面试题】)