1. 题目描述
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。
示例 1:
输入:x = 121
输出:true
2. 题解
c++:
注意返回值不能再是int类型。
class Solution {
public:
bool isPalindrome(int x) {
bool isPalindrome;
int tmp = x;
int end = 0;
long long reverse_result = 0;
if ( x < 0) {
return false;
}
while(tmp != 0) {
end = tmp%10;
tmp = tmp/10;
reverse_result = end + reverse_result*10;
}
if (reverse_result == x) {
return true;
} else {
return false;
}
}
};
优化下:
class Solution {
public:
bool isPalindrome(int x) {
bool isPalindrome;
int tmp = x;
int end = 0;
long long reverse_result = 0;
if ( x < 0) {
return false;
}
while(tmp) {
reverse_result = tmp%10 + reverse_result*10;
tmp = tmp/10;
}
return reverse_result == x;
}
};
评论 (0)