LeetCode 9
Palindrome Number
Problem Description:
Determine whether an integer is a palindrome. Do this without extra space.Hints:
1. Could negative integers be palindromes? (ie, -1)
2.If you are thinking of converting the integer to string, note the restriction of using extra space.
3. You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?Solution:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0)
return false;
int n;
string result = "";
int flag = 0;
while(x != 0) {
n = x%10;
result += n+'0';
x = x/10;
}
for (int i = 0; i < result.length()/2; i++) {
if (result[i] == result[result.length()-i-1]) {
continue;
}
flag = 1;
}
if (flag == 0)
return true;
return false;
}
};
本文介绍了一种不使用额外空间判断整数是否为回文数的方法。通过对整数进行位操作,将其转换为字符串形式,并通过双指针技术验证其正反顺序是否一致来实现。文章还探讨了负数是否可以作为回文数以及如何避免反转整数过程中可能出现的溢出问题。

415

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



