-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9-palindrome-number.cpp
38 lines (30 loc) · 1.04 KB
/
9-palindrome-number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Title: Palindrome Number
// Description:
// Given an integer x, return true if x is a palindrome, and false otherwise.
// Follow up: Could you solve it without converting the integer to a string?
// Link: https://leetcode.com/problems/palindrome-number/
// Time complexity: O(1)
// Space complexity: O(1)
class Solution {
public:
bool isPalindrome(int x) {
// negative numbers can never be palindromes
if (x < 0) return false;
// x is a palindrome if x == reverse(x)
return x == reverse(x);
}
int reverse(int n) {
// only non-negative numbers can be reversed
assert(n >= 0);
int result = 0;
// take each digit in n
for (int tmp = n; tmp != 0; tmp /= 10) {
int digit = tmp % 10;
// return INT_MIN if result is unrepresentable in int
if (result > (INT_MAX - digit) / 10) return INT_MIN;
// append the digit to the result
result = (result * 10) + digit;
}
return result;
}
};