Skip to content

Commit

Permalink
feat: Add solution for palindrome number with test cases.
Browse files Browse the repository at this point in the history
  • Loading branch information
VishwajeetVT committed Sep 19, 2024
1 parent 05caef6 commit e9297fc
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.practice.dsa.leet_code.easy;

public class QuestionPalindrome {
/*
* Given an integer x, return true if x is a palindrome, and false otherwise.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
* */

public boolean isPalindrome(int x) {

if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}

int reverseHalf = 0;
while (x > reverseHalf) {
reverseHalf = reverseHalf * 10 + reverseHalf % 10;
x /= 10;
}
// For odd number of digits, we discard the middle digit by dividing reversedHalf by 10
return x == reverseHalf || x == reverseHalf / 10;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package org.practice.dsa.leet_code.easy;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class TestPalindrome {
private QuestionPalindrome palindrome = new QuestionPalindrome();

@Test
public void testNumberIsPalindrome() {
boolean result = palindrome.isPalindrome(121);
assertTrue(result);
}

@Test
public void testIsPalindromeForNegativeNumber() {
assertFalse(palindrome.isPalindrome(-121));
}

@Test
public void testPalindromeIfNumberIsZero() {
assertTrue(palindrome.isPalindrome(0));
}

@Test
public void testPalindromeNumber() {
assertFalse(palindrome.isPalindrome(10));
assertFalse(palindrome.isPalindrome(550));
}
}

0 comments on commit e9297fc

Please sign in to comment.