This one was a little more tricky than the last.
Name: Palindrome Number
Difficulty: Easy
Description: Return true if a number reads the same backwards, false otherwise.
Example:
Given 121 return true Given 10 return false Given -121 return false, because 121- is not the same as -121.
To solve this problem, I first copied the original number (x) to another variable (target). I need to preserve target for the final comparison, but need to mutate x to get the reverse value.
The reverse value (y) is initialized to zero. Looping over x I multiply y by 10. Using modular, I then get the last digit of x and add it to y. Lastly, I remove the last digit from x.
Performance was pretty good, but a bit high on the memory usage:
bool isPalindrome(int x) {
if (x < 0) return false;
uint target = x;
uint y = 0;
while (x > 0) {
y = y * 10 + x % 10;
x /= 10;
}
return target == y;
}