简体   繁体   中英

Why doesn't a compareTo BigInteger while loop exit?

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;
}

I ran your code and it works fine; the while loops exits.

Your code does have 2 bugs in it:

  • in the .add(auxNum.divide) call I assume you want mod instead.
  • you can't compare bigints with == . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM