0%

Reverse Integer

题目描述

Given a 32-bit signed integer, reverse digits of an integer. Returns 0 when the reversed integer overflows.

Example 1:

1
2
Input: 123
Output: 321

Example 2:

1
2
Input: -123
Output: -321

Example 3:

1
2
Input: 120
Output: 21

解决方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int reverse(int a)
{
long long b = 0;
long long tmp = a;
if (a<0)
tmp *= (-1);
int mod = 10;
int k = 0;
while (tmp > 0)
{
k = tmp % (mod);
tmp /= mod;
b *= 10;
b += k;
}
b=(a > 0) ? b : (-1)*b;
if (b > INT_MAX || b < INT_MIN)
return 0;
return b;
}

主要需要注意的地方是int和long long数据类型的区别。使用INT_MAX和INT_MIN可以表示int类型的最值。

unsigned int 0~4294967295
int -2147483648~2147483647 [$−2^{31}, 2^{31} − 1​$]
unsigned long 0~4294967295
long -2147483648~2147483647
long long的最大值:9223372036854775807
long long的最小值:-9223372036854775808
unsigned long long的最大值:1844674407370955161