
Solving Code
public class Palindrome {
public boolean isPalindrome(int x) {
if (x < 0) return false;
if (x != 0 && x % 10 == 0) return false;
int reverse = 0;
while (x > reverse) {
int lastDigit = x % 10;
reverse = reverse * 10 + lastDigit;
x = x / 10;
}
return (x == reverse) || (x == reverse / 10);
}
}
Test Code (JUnit)
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class PalindromeTest {
private final Palindrome palindrome = new Palindrome();
@Test
void testSimpleIsPalindrome() {
assertTrue(palindrome.isPalindrome(12321));
}
@Test
void testFalseIsPalindrome() {
assertFalse(palindrome.isPalindrome(12312));
}
@Test
void testOnlyZero() {
assertTrue(palindrome.isPalindrome(0));
}
@Test
void testTen() {
assertFalse(palindrome.isPalindrome(10));
}
}
Top comments (0)