Palindrome Number
(Solution to LeetCode easy problem)
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.
Example 1:
Input: x = 121
Output: true
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.
Example 4:
Input: x = -101
Output: false
Constraints:
-2^31 <= x <= 2^31 - 1
Brute-Force Approach
This is a basic approach where I will convert the integer to a string, I will traverse the string from index 0 to n/2 where n is the size of the string. I will simply compare the first string element to the last string element, if it does not satisfy then I will return false else I will keep incrementing the value of I and keep checking.
Time Complexity: O(|n|) where n is the length of the string
Space Complexity: O(1)
Here is the code is given below.
class Solution {
public:
bool isPalindrome(int x) {
string s = to_string(x);
int i = 0, j = s.size();
while(i<=j/2)
{
if(s[i]!=s[j-i-1])
{
return false;
break;
}
i++;
}
return true;
}
};
This is the simplest solution from where you can begin solving the question. I would want you to try to optimize the above solution into fewer time complexities. Comment down your solutions and let’s see which of those is the most efficient solution!
Stay tuned for more, till that time keep practicing!! Good luck!!!💻🙌
If you enjoyed reading my blog , why not buy me a coffee and supoort my work here!! https://www.buymeacoffee.com/sukanyabharati ☕