【leetcode】Reverse Integer

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/guorong520/article/details/81134145
题目描述
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).

整数的范围而:-2147483648~2147483647
解析:其实就是将整数翻转过来,需要注意的是,翻转的结果有可能溢出,就好比有一个数2100000003,此时你进行翻转后,它就超过了Int的范围,所以应该定义为long。

代码:

#include <stdio.h>
int reverse_integer(int x)
{
    long res=0;
    while(x!=0)
    {
        res=res*10+x%10;
        x/=10;
    }
    return (res>INT_MAX||res<INT_MIN)?0:res;
}
//INT_MAX与INT_MIN是两个宏,保存了整数的最大值和最小值。

猜你喜欢

转载自blog.csdn.net/guorong520/article/details/81134145