9. Palindrome Number
Problem
Tags: Math
Given an integer x
, return true
if x
is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
- For example,
121
is a palindrome while123
is not.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-2^31 <= x <= 2^31 - 1
Follow up: Could you solve it without converting the integer to a string?
Code
C
// 9. Palindrome Number (11/15/53956)
// Runtime: 8 ms (84.94%) Memory: 6.07 MB (18.87%)
bool isPalindrome(int x){
// x 是負數,直接 false
if(x < 0) return false;
// y 用來存 x 的反轉數
int64_t reversed = 0;
// 從最後一位開始,每次將 reversed 左推後加上該位之值
for(int64_t num = x; num > 0; num /= 10) {
reversed = reversed * 10 + num % 10;
}
// 比較兩者是否相等
return (int64_t)x == reversed;
}