Category : Easy
Problem
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string?
https://leetcode.com/problems/palindrome-number/
Examples
Example 1:
1 2 | Input: x = 121 Output: true |
Example 2:
1 2 3 4 | 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:
1 2 3 | Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. |
Example 4:
1 2 | Input: x = -101 Output: false |
Constraints
-231 <= x <= 231 - 1
Solution Approach
To check if the number is palindrome or not we just reverse the number by taking out the last digit from the number one by one and concatenating those digits to a new reverse number. In the end, we will compare those two numbers (original and the concatenated reverse number) and if they are equal then we can say that the number is palindrome otherwise they are not.
Solution code
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Solution { public boolean isPalindrome(int x) { int num = x, rev = 0; if(x<0) return false; while(x!=0){ int d = x%10; x = x/10; rev = rev*10 + d; } return (rev==num); } } |
For more Leetcode explained solutions visit Leetcode Solutions. If you like capture the flag challenges visit here.
Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via Contact page I will surely respond. Happy Leetcoding
Pingback: Leetcode 1295: Find Numbers with Even Number of Digits - Cse Nerd
Pingback: Leetcode 728: Self Dividing Numbers - Leetcode Detailed Solutions