DuckStudyingJava - 5 months ago 18

Java Question

I'm doing some exercise programs in Java and came to this palindrome number exercise which tells if the number is palindrome, I'm getting the correct output but I'm trying to explain to myself how the program is working line by line, upon reaching a specific line I noticed that that part doesn't seem to add up, here is the code:

`public class Palindrome {`

public static void main(String[] args) {

int p = 252;

if(isPalindrome(p)) {

System.out.println("Palindrome");

} else {

System.out.println("Not palindrome");

}

}

public static boolean isPalindrome(int x) {

int num = x;

int rev = 0;

while (num != 0) {

int rmd = num % 10;//the remainder of 252 is 2

rev = rev * 10 + rmd;//rev which is 0 multiplied by 10 is 0 + 2 is 2

num = num / 10;

}

if (x == rev) {//x = 252 and rev = 2

return true;

}

return false;

}

}

in the part:

`if(x == rev)`

Answer

You have to look what happens during the loop as it goes through its iterations.

For simple programs, such as this one, a paper-and-pencil approach works fine. For more complex programs adding "debug prints" help you understand what is going on:

```
int iterationCount = 0;
while (num != 0) {
System.out.println("Before iteration="+iterationCount+" num="+num+" rev="+rev);
int rmd = num % 10;//the remainder of 252 is 2
rev = rev * 10 + rmd;//rev which is 0 multiplied by 10 is 0 + 2 is 2
num = num / 10;
System.out.println("After iteration="+iterationCount+" num="+num+" rev="+rev);
iterationCount++;
}
```

This produces the following output:

```
Before iteration=0 num=252 rev=0
After iteration=0 num=25 rev=2
Before iteration=1 num=25 rev=2
After iteration=1 num=2 rev=25
Before iteration=2 num=2 rev=25
After iteration=2 num=0 rev=252
Palindrome
```

Note how `num`

decreases down to zero, while `rev`

grows to `252`

with each iteration.