Search code examples
javasymmetric

cheking on symmetric number


How check number on symmetrics?

public static int Symmetric(int a) {
    if(new StringBuilder(Integer.toString(a)) ==
        new StringBuilder(Integer.toString(a)).reverse())
        return  a;
    else
        return 0;
}

I try do it smth like this but always return 0.


Solution

  • You can't use == to compare Strings (or StringBuilders), you need to use equals().
    Also, you need to turn the StringBuilders back to Strings before comparing:

    EDIT: Also, there is really no need for the first StringBuilder:

    public static int symmetric(int a) {
        if (Integer.toString(a).equals(new StringBuilder(Integer.toString(a)).reverse().toString()))
            return a;
        else
            return 0;
    }