Palindrome Number
Easy · Math · Math
Problem
Given an integer x, return true if its decimal digits read the same forwards and backwards, and false otherwise.
A negative number is never a palindrome: its minus sign appears only on the left. Try to solve it without turning the number into a string.
Examples
Input: x = 1331 Output: true
1331 read backwards is still 1331.
Input: x = -44 Output: false
Read right to left it is 44-, which is not the same.
Input: x = 120 Output: false
Backwards it would be 021, which is not 120.
Constraints
- -2^31 <= x <= 2^31 - 1
Approaches
- Baseline: compare the string with its reverse — time O(log x), space O(log x)
Follow-up
Reversing the whole number can overflow a 32-bit integer in languages with fixed-size integers (try 2,147,483,647 backwards). Why does reversing only half the digits never overflow?
Related problems
Start free on Cariara · Coding problems · System design studio