您的位置:首页 > 其它

【LeetCode刷题记录】Reverse Integer

2015-05-07 21:49 489 查看

题目

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

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?

解答

题意很明确,把一个十进制数逆序表示。

首先,只考虑如何实现逆序。和Reverse Bits相似,从低位开始。x%10得到最低位,x/10相当于右移1位,然后在处理下一位之前,对已经产生的结果乘以10,不断把低位往高位移动。

然后,就掉进坑里面了。显然,对于32位的int来说,表示范围为[-2^31, 2^31](即-2147483648~2147483647)。最明显的特例是当x=2147483647时,逆序之后的数是超出int32的表示范围的。所以,需要进行判断。

自己没想出来,在讨论区里找到一个好方法:使用long long类型保存逆序之后的中间结果,它可以表示32位int逆序之后的所有数;然后再判断其大小有没有超出32位int的表示范围。

通过这题,又一次深刻地认识到数据类型的妙用。AC代码如下:

[code]int reverse(int x) {
    if (x == 0)
        return 0;
    long long ret = 0;

    while (x != 0) {
        ret = ret*10;
        ret += x%10;
        x = x/10;
    }

    return (ret > INT_MAX || ret < INT_MIN) ? 0 : ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: