索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
题目:https://oj.leetcode.com/problems/palindrome-number/
代码(github):https://github.com/illuz/leetcode
判断一个数是否是回文数。
按自己想的去写就行了。
C++:(可以先转为字符串)
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int bit[10];
int cnt = 0;
while (x) {
bit[cnt++] = x % 10;
x /= 10;
}
for (int i = 0; i < cnt; i++)
if (bit[i] != bit[cnt - i - 1])
return false;
return true;
}
};
Python:
class Solution:
# @return a boolean
def isPalindrome(self, x):
return str(x) == str(x)[::-1]
C++:(算出回文)
class Solution {
public:
bool isPalindrome(int x) {
long long xx = x;
long long new_xx = 0;
while (xx > 0) {
new_xx = new_xx * 10 + xx % 10;
xx /= 10;
}
return new_xx == (long long)x;
}
};
Java:
public class Solution {
public boolean isPalindrome(int x) {
long xx = x;
long new_xx = 0;
while (xx > 0) {
new_xx = new_xx * 10 + xx % 10;
xx /= 10;
}
return new_xx == x;
}
}
Python:
class Solution:
# @return a boolean
def isPalindrome(self, x):
xx = x
new_xx = 0
while xx > 0:
new_xx = new_xx * 10 + xx % 10
xx /= 10
return new_xx == x