-2

Just trying to check if the input is a palindrome. Code keeps evaluating to true, but upon debugging, my answers are false;

Maybe I'm confused with == vs .equals?

class Solution {
    public boolean isPalindrome(int x) {
        int orig = x;
        String result = x + "";
        char[] original = result.toCharArray();
        String compare = "";

        if(orig < 10) {
            return true;
        }

        for(int i = original.length-1; i >= 0; i--) {
            compare += original[i];  
        }

        //System.out.println(result); -121
        //System.out.println(compare); 121
        if(result == compare) {
            return true;
        } else {
            return false;
        }   
    } 
}
learning
  • 19
  • 5

1 Answers1

0

Assuming you used (result==compare) Replace it with result.equals(compare)

Shashank Gupta
  • 321
  • 3
  • 15
  • Won’t work if the number is negative – Harshal Parekh May 28 '19 at 19:04
  • Can you explain why? @HarshalParekh The string contents are still different? – learning May 28 '19 at 19:11
  • Based on the logic of the code, if a number is negative, say -121, @learning is trying to convert it to a string and then reverse it. In this case, you’re comparing -121 with 121- which logically is a palindrome, but your logic will return false. Your solution only fixes the problem with positive numbers. – Harshal Parekh May 28 '19 at 19:15
  • I am not sure about this but can a negative number be a palindrome? – Shashank Gupta May 29 '19 at 05:20