Given an integer n, return true if it reads the same forwards and backwards, and false otherwise. Negative numbers are not palindromes because of the leading minus sign.
Palindrome Number
SolvedExamples:
Input: n = 12321
Output: true
Explanation: Reversed, 12321 is still 12321.
Input: n = -121
Output: false
Explanation: Reversed it would be 121-, which is not the same.
Input: n = 10
Output: false
Explanation: Reversed it is 01.
Constraints:
-10^18 ≤ n ≤ 10^18
Expected Complexities
Time Complexity: O(log n) Auxiliary Space: O(1)
Company Tags
Topic Tags
Build the reversed number digit by digit: peel off the last digit with n % 10 and append it to the reverse with reverse * 10 + digit. Compare at the end. Rejecting negatives up front keeps the loop simple.
class Solution {
public boolean isPalindrome(long n) {
if (n < 0) return false;
long original = n, reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return original == reversed;
}
}
Sign in to see your submissions.