The question asked on leetcode is: Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
This is my code.
class Solution {
public boolean isPalindrome(int x) {
if (x <= 9) {
//negative numbers are not palindromes
if (x < 0) {
return false;
}
}
else {
return true;
}
//if anything is divisible by 10 with no remainders its not a palindrome
if (x % 10 ==0) {
return false;
}
//creating reverse method
int reverse = 0;
while(x > reverse) {
int num = x % 10;
x /= 10;
reverse = (reverse * 10) num;
}
if (x == reverse || x == reverse / 10) {
return true;
}
else {
return false;
}
}
}
I'm quite sure my logic is correct but I test on NetBeans with no seen errors and receive 121 being a correct answer but 10 is showing up as true when it should be false due to not being a palindrome? I'm confused and would like some help with understanding the logic a little better.
CodePudding user response:
You could achieve the same thing by:
- Decomposing your number into digits. You can use
ArrayList
. - Comparing every
i
th element with then-i
th
import java.util.ArrayList;
public class Main {
public static boolean palindrome(int number)
{
if (number < 0)
number *= -1; // Or return false if you want to exclude negative numbers
// 1. Decompose the number into digits
ArrayList<Integer> digits = new ArrayList<Integer>();
while (number > 0) {
digits.add(number % 10);
number /= 10;
}
// 2. Check
for (int i = 0, j = digits.size()-1; i < j; i , j--) {
if (digits.get(i) != digits.get(j))
return false;
}
return true;
}
public static void main(String[] args)
{
System.out.println(palindrome(121));
System.out.println(palindrome(123));
System.out.println(palindrome(10));
}
}
Output:
true
false
false
CodePudding user response:
The issue is with the first check - you always return true for any number bigger than 9.
This:
if (x <= 9) {
//negative numbers are not palindromes
if (x < 0) {
return false;
}
}
else {
return true;
}
Should've been this:
if (x <= 9) {
//negative numbers are not palindromes
if (x < 0) {
return false;
}
else {
return true;
}
}
And even this is way too verbose. Simpler way to write same logic is
if (x <= 9) {
//negative numbers are not palindromes, but positive single digit numbers are
return x >= 0;
}