一、问题描述
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
二、思路及注意事项
- 注意最后的说明,如果超限,则返回0。
- 不需要考虑正负号的影响
- 注意特殊数字-2147483648 = -(2^31),取绝对值时会超限溢出。
- 查看以下示例中,判断数据是否溢出的方法
- 还是通过示例计算,查看数据计算规则
- 32位有符号整数的范围:-(2^31) ~ (2^31)-1
- 32位有符号整数中,负数比正数个数多1个。
- **32位无符号整数的范围:**0~(2^32)-1
三、程序示例(共4种方法)
C#版本
class Program
{
//自己最开始写的。
//不过超限溢出并没注意。
//直到提交时当输入为-2147483648时,
//报错后才发现题目的溢出提醒。
//此处溢出判断参考官方给出的答案。
public static int reverse1(int x)
{
int temp = x;
int remain = 0;
int reverse = 0;
while (temp!=0)
{
remain = temp % 10;
temp = temp / 10;
//注意该判断,是否超限溢出
if (Math.Abs(reverse) > int.MaxValue / 10)
{
return 0;
}
reverse = reverse * 10 + remain;
}
return reverse;
}
public static int reverse2(int x)
{
int res = 0;
while (x != 0)
{
//官方给出的答案:注意该判断,是否超限溢出
if (Math.Abs(res) > int.MaxValue / 10) return 0;
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
//通过高级数据类型,解决溢出问题
public static int reverse3(int x)
{
long res = 0;
while (x != 0) {
res = 10 * res + x % 10;
x /= 10;
}
return (res > int.MaxValue || res < int.MinValue) ? 0 : (int)res;
}
//溢出判断的另外一种方法
public static int reverse4(int x)
{
int res = 0;
while (x != 0)
{
int t = res * 10 + x % 10;
if (t / 10 != res) return 0;
res = t;
x /= 10;
}
return res;
}
static void Main(string[] args)
{
//int num = 123;
int num = -2147483648;
int result = reverse4(num);
}
}
感谢博主的分享。
http://www.cnblogs.com/grandyang/p/4125588.html
2018.03.16:更新有符号与无符号32位整数的范围。