LeetCode 9. Palindrome Number
Solution1:
不利用字符串
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int res = 0, base = 1, x_copy = x;
while (x_copy) {
res = res * 10 + x_copy%10;
x_copy /= 10;
}
if (res != x)
return false;
else
return true;
}
};
Solution2:
利用字符串
就是有点慢!
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
string str_x = to_string(x);
int left = 0, right = str_x.size() - 1;
while (left < right) {
if (str_x[left] != str_x[right])
return false;
else {
left++;
right--;
}
}
return true;
}
};
本文提供两种方法来判断一个整数是否为回文数:一种是不使用字符串转换,直接通过数学操作实现;另一种是将整数转换成字符串后进行比较。第一种方法效率较高,适合对性能要求严格的场景。
242

被折叠的 条评论
为什么被折叠?



