7. Reverse Integer
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.
class Solution {
public:
int reverse(int x) {
}
};
解题思路:
-
自己的解题思路
因为要考虑溢出情况,所以经典的转换方法不能直接用,需要做点改变。
10000 00003 倒序后变成30000 00001会出现溢出情况。
我的方法是:用个string str_max来记录MAX_INT,则【-MAX_INT, MAX_INT】可以通过转化为【0, MAX_INT】来解决问题。对于MIN_INT直接处理。
题目明确说了,
溢出返回0
。
-
别人的解题思路
通过用long long 来记录int值,不推荐用long. 这样就可以直接用经典倒序算法直接对int x进行倒序。此方法很巧妙,需突破思维禁锢。
同时,他将正数跟负数一起处理,不需要分情况讨论。
学习收获:
-
学到一招,小范围数转到大范围数,来防止溢出。
-
对于已知一个string str;求它的倒序,可以string temp(str.rbegin(), str.rend());
还要更简单的方法?可以直接对它进行倒序?
附件:程序
1、自己的程序:
int
reverse
(
int
x
)
{
if
(
INT_MIN
==
x
)
{
return
0
;
}
int
ux
=
(
x
>
0
)
?
x
:
-
x
;
int
flag
=
(
x
>
0
)
?
1
:
-
1
;
int
temp
=
ux
;
int
len
=
0
;
while
(
temp
)
{
len
++;
temp
/=
10
;
}
if
(
len
<
10
)
{
int
res
=
0
;
while
(
ux
)
{
res
=
res
*
10
+
ux
%
10
;
ux
/=
10
;
}
return
res
*
flag
;
}
else
{
string
str1
,
str
;
int
max_tem
=
INT_MAX
;
temp
=
ux
;
while
(
temp
)
{
str1
.
push_back
(
temp
%
10
+
'0'
);
str
.
push_back
(
max_tem
%
10
+
'0'
);
temp
/=
10
;
max_tem
/=
10
;
}
string
str_max
(
str
.
rbegin
(),
str
.
rend
());
if
(
str1
>
str_max
)
{
return
0
;
}
else
{
int
res
=
0
;
while
(
ux
)
{
res
=
res
*
10
+
ux
%
10
;
ux
/=
10
;
}
return
res
*
flag
;
}
}
}
2、别人的程序
int
reverse
(
int
x
)
{
long long
r
=
0
;
while
(
x
)
r
=
r
*
10
+
x
%
10
,
x
/=
10
;
return
(
int
(
r
)
==
r
)
*
r
;
}
本文介绍了一种有效的整数反转算法,解决了整数反转过程中可能遇到的溢出问题,并提供了两种不同的实现方法,一种适用于较长数字串,另一种则利用long long类型简化了处理过程。
223

被折叠的 条评论
为什么被折叠?



