反转两次的数字
难度:
标签:
题目描述
代码结果
运行时间: 22 ms, 内存: 16.1 MB
/*
* The goal is to check if reversing an integer twice results in the original number using Java Streams.
* 1. Convert the integer to a string and reverse it using a stream.
* 2. Convert the reversed string back to an integer and repeat the process.
* 3. Compare the final result with the original number.
*/
import java.util.stream.Collectors;
public class Solution {
public boolean isSameAfterReversals(int num) {
// First reversal
int reversed1 = reverse(num);
// Second reversal
int reversed2 = reverse(reversed1);
// Check if the double-reversed number is the same as the original
return num == reversed2;
}
private int reverse(int num) {
String reversedString = new StringBuilder(String.valueOf(num)).reverse().toString();
return Integer.parseInt(reversedString);
}
}
解释
方法:
题目要求判断一个数字反转两次后是否与原数字相同。首先,任何数字反转两次理论上应该回到原始状态。但特殊情况是,如果一个数字的末尾有0,第一次反转后会丢失这些0(不保留前导零),导致第二次反转后的数字不等于原始数字。因此,只需检查数字是否为0或其末尾是否有0。如果数字是0,它经过两次反转仍然是0;如果数字末尾有0(且数字不是0),则反转两次后数字会变,返回false。否则,返回true。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
在解题思路中提到,'如果一个数字末尾有0,第一次反转后会丢失这些0',为什么数字末尾的0在反转后会消失?
▷🦆
提到如果数字是0,两次反转后仍然是0。能否举例说明为什么任何非零数字末尾没有0的条件下,两次反转后必定与原数字相同?
▷🦆
在代码中使用`num % 10 == 0`来判断数字是否以0结尾,这种方法是否可靠,存在没有考虑的边界情况吗?
▷🦆
为什么在解释'数字两次反转后应该和原数字相同'时没有提到反转过程中可能遇到的其他异常或特殊情况?
▷