我给出了以下代码片段来帮助我解决涉及数字回文的问题.我无法弄清楚这是如何工作的.我知道它涉及while循环,但我无法遵循逻辑.
public static boolean isPalindrome(int nr) {
int rev = 0;
int x = nr;
while (x > 0) {
rev = 10 * rev + x % 10;
x /= 10;
}
return rev == nr;
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释这是如何工作的吗?
如果数字是回文数,那么rev将在循环结束后等于数字.这是它的工作原理,示例迭代在nr121:
public static boolean isPalindrome(int nr) {
int rev = 0;
int x = nr; // 121
while (x > 0) {
rev = 10 * rev + x % 10; // x % 10 is the last digit of x when in base 10. multiplying the previous value of rev by 10 and adding x % 10 is adding the last digit of x to the next digit of rev
// step 1: rev = 10*0 + 1 = 1
// step 2: rev = 10*1 + 2 = 12
// step 3: rev = 10*12 + 1 = 121
x /= 10; // truncates the last digit of x
}
Run Code Online (Sandbox Code Playgroud)
所以return语句应该是 return rev == nr;
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |