Why my code for checking if a number is a palindrom won't work?

后端 未结 5 1638
逝去的感伤
逝去的感伤 2021-01-29 06:28

My Java code is here:

import java.util.Scanner;
public class task2 {
    public static void main(String args[])  {
        System.out.print(\"Input a 3 digit int         


        
5条回答
  •  囚心锁ツ
    2021-01-29 07:04

    When you do the following operation on x:

    x /= 10;
    

    you're modifying its value - so it no longer contains the input from:

    int x = scan.nextInt();
    

    As Narendra Jadon suggested - you can save the original value into another variable and use it when you try to compare:

    if (x == isPalindrome){
    

    Alternative solution that uses "conversion" of the int to String:

    public boolean isPalindrom(int n) {
        return new StringBuilder("" + n).reverse().toString().equals("" + n);
    }
    

提交回复
热议问题