问题描述
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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
这题是easy的分类,意思是输入一个整数,输出这个整数的reverse版本,即倒序输出每一位。需要注意的是数字的大小有可能会超过32位表示的最大范围所以需要特殊处理。
解题思路
brute force, 每次取出一位数字然后判断越界情况,如果越界直接返回最大或最小数
代码实现
public int reverse(int x) {
int res = 0;
while(x != 0) {
int bit = x % 10;
x = x / 10;
if(res > Integer.MAX_VALUE / 10 || res < Integer.MIN_VALUE / 10)
return 0;
else
res = res * 10 + bit;
}
return res;
}
注:因为输入本身是一个32位的整数,所以当值接近最大或最小值的时候首位最大就是2, 所以情况简单了很多。
注2: 这题还有一个很鸡贼的做法,因为我的程序空间复杂度太低我就看了一下大佬们怎么做,发现有人直接定义了一个long的数字,然后直接强行做然后转换为int了。
复杂度分析
对于整数x,一共有log10(x)位数,所以一种这么多次循环,每次循环时间复杂度是O(1),所以总的时间复杂度是O(log(x)), 空间复杂度是O(1)
分析
没有什么难点所以没什么分析