Reputation: 17
I have this method that is stuck in a while loop, I print the boolean value of the condition in the method itself and it does eventually get to be false but it will not exit the cycle.
public static boolean isPalindrome(BigInteger num) {
BigInteger invertedNum = BigInteger.valueOf(0);
BigInteger auxNum = num;
while (auxNum.compareTo(BigInteger.valueOf(0)) != 0) {
invertedNum = invertedNum.multiply(BigInteger.valueOf(10)).add(auxNum.divide(BigInteger.valueOf(10)));
auxNum = auxNum.divide(BigInteger.valueOf(10));
System.out.println(auxNum.compareTo(BigInteger.valueOf(0)) != 0);
}
return invertedNum == num;
}
Upvotes: 0
Views: 123
Reputation: 103273
I ran your code and it works fine; the while loops exits.
Your code does have 2 bugs in it:
.add(auxNum.divide)
call I assume you want mod
instead.==
. You must use .equals
(in the while loop you use .compareTo
which works fine, but .equals
is more readable, in that it correctly expresses what you're trying to accomplish. You're comparing with == at the very end, in the return
statement.Applying those 2 fixes, your code correctly returns true for palindromic (in decimal) numbers, and false otherwise.
Upvotes: 3