9. Palindrome Number
Asked at 30Google74Microsoft73Bloomberg72Amazon70Meta66tcs89Accenture84Infosys73Yandex36Bosch100Cognizant89PornHub87SAP81LTI81Qualcomm76Wipro73Morgan Stanley72MindTree71Deloitte71AMD69Intel66IBM63HCL60Capital One56Capgemini52Zoho52EPAM Systems51Oracle41Nvidia39Cisco37
Problem
Decide whether the integer x reads the same forwards and backwards.
Example: 121 → true; -121 → false; 10 → false
Constraints: follow-up: without converting to a string.
Negative numbers and numbers ending in 0 (except 0) aren't palindromes. Reverse only the second half of the digits and compare with the first half — no overflow risk.
Complexity: O(log x).
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x % 10 == 0 and x != 0):
return False
rev = 0
while x > rev:
x, d = divmod(x, 10)
rev = rev * 10 + d
return x == rev or x == rev // 10
assert Solution().isPalindrome(121) is True
assert Solution().isPalindrome(-121) is False
assert Solution().isPalindrome(10) is False
assert Solution().isPalindrome(1221) is True
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int rev = 0;
while (x > rev) { rev = rev * 10 + x % 10; x /= 10; }
return x == rev || x == rev / 10;
}
}
func isPalindrome(x int) bool {
if x < 0 || x%10 == 0 && x != 0 {
return false
}
rev := 0
for x > rev { // reverse only the second half
rev = rev*10 + x%10
x /= 10
}
return x == rev || x == rev/10 // odd length: drop the middle digit
}