LeetCode:Reverse Integer

Total Accepted: 100793 Total Submissions: 429248 Difficulty: Easy
Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321

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? For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. Update (2014-11-10): Test cases had been added to test the overflow behavior.

Tags
Math

Hide Similar Problems
(E) String to Integer (atoi)

Discuss
来源: https://leetcode.com/problems/reverse-integer/

代码(Accepted):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int reverse(int x) {
int ret = 0;
while(x!=0){
if(ret>INT_MAX/10||ret<INT_MIN/10){
return 0;
}
ret = ret*10 + x%10;
x = x/10;
}
return ret;
}
};
 我感觉最准确的应该是下面这个
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int reverse(int x) {
int ret = 0;
while(x!=0){
if(ret>INT_MAX/10-x%10/10||ret<INT_MIN/10-x%10/10){
return 0;
}
ret = ret*10 + x%10;
x = x/10;
}
return ret;
}
};

Solution:

To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why?

相关链接:

http://blog.csdn.net/nomasp/article/details/48675979

int型整数的最小值和最大值 http://bbs.csdn.net/topics/340223320

本题解析:

本题一定要把判断加在while循环之中,并且要在乘10之前判断是否超出范围。

遗留问题:

1.两段代码更精确的感觉应该是下面那个。
2.运行时间8ms,比较长,有待优化。(your runtime beats 24.74% of cpp submissions.)

相关知识点:

  1. 整数最大值和最小值
    INT_MAX和INT_MIN定义在limits.h中。
    INT_MAX #define INT_MAX 2147483647
    INT_MIN #define INT_MIN (-2147483647 – 1)
    注意:其中INT_MIN最小值没有写成-2147483647,是因为-2147483648对于编译器而言是个表达式,而2147483648对于32-bit整数是无法表示的,所以经过这个表达式的结果是未定义的。在GCC上直接写-2147483648后,编译器给出了警告,说结果是unsigned。可参考 INT_MIN.
    也可用以下写法(推荐):
    1
    2
    #define MAX_INT ((unsigned)(-1) >> 1)
    #define MIN_INT (int)(MAX_INT + 1)