Home > Software engineering >  Palindrome number check- issue with output
Palindrome number check- issue with output

Time:03-26

I tried to write a program to check whether a number is a palindrome or not in Java. I tried to convert int to String, and using built-in methods, wrote this logic. But I don't know why I am getting incorrect output for the given input.

class Main {
    public static void main(String[] args) {
        int x=1213;
        
        StringBuilder s= new StringBuilder();
        s.append(x);
        StringBuilder s2=new StringBuilder();
        s2=s.reverse();
       
        
        if((s.toString()).equals(s2.toString()))
        {
           System.out.println(x " is a palindrome number");
        }
        else{
            System.out.println(x "is not a palindrome number");
        }
    }

CodePudding user response:

 s2=s.reverse();

Here the StringBuilder class is not immutable , reverse operation will reverse the content of the original the StringBuilder s, you should construct a new StringBuilder here :

public class Main {
public static void main(String[] args) {
    int x=1213;
    
    StringBuilder s= new StringBuilder();
    s.append(x);
    StringBuilder s2=new StringBuilder();
    s2=new StringBuilder(s).reverse();
   
    
    if((s.toString()).equals(s2.toString()))
    {
       System.out.println(x " is a palindrome number");
    }
    else{
        System.out.println(x "is not a palindrome number");
    }
}
}

CodePudding user response:

You call s.reverse(), which reverses s in place; and you assign it to s2, so s and s2 are the same object.

You don't need two StringBuilders at all, since you only need to make one modification.

StringBuilder sb = new StringBuilder();
sb.append(x);
sb.reverse();
if (sb.toString().equals(String.valueOf(x))) {
    // the number is a palindrome
}
  •  Tags:  
  • java
  • Related