7.Reverse digits of an integer.
Problem descriptions:
Example1: x = 123, return 321
Example2: x = -123, return -321
Difficulty:Easy
class Solution {
public:
int reverse(int x) {
long long int y= 0,z=0;
int res = 0;
z = x;
if(x<0)
{
z = -z;
}
y = z%10;
z = z/10;
while(z>0)
{
y = y * 10 + z%10;
z = z /10;
}
if(x<0)
{
y = -y;
}
if (y >= INT_MAX)
{
res = 0;
}
else if (y<= INT_MIN)
{
res = 0;
}
else
{
res = (int)y;
}
return res;
}
};
注意正负、取值范围就OK了
本文介绍了一个简单的整数反转算法,该算法能够正确处理包括负数在内的整数,并确保结果在整数范围内有效。通过示例展示了如何将123转换为321,以及-123转换为-321的过程。
1506

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



