求一个数字是否为回文
[2017-11-23修改:增加字符串回文判断]
先写一个本人的笨办法,不过可以判断负数,该方法把整个数字每一位都存了下来(其实可以只存一半):
bool isPalindrome(int x)
{
int temp = x;
vector<int> vec;
while (temp)
{
vec.push_back(temp % 10);
temp /= 10;
}
std::reverse(vec.begin(), vec.end()); //从后往前比较
//只需要比较一半即可
for(int i = 0; i < vec.size() / 2 + 1; ++i)
{
if (x % 10 != vec[i])
{
return false;
}
x /= 10;
}
return true;
}
接下来是LeetCode的解法:
bool IsPalindrome(int x) {
// As discussed above, when x < 0, x is not a palindrome.
// Also if the last digit of the number is 0, in order to be a palindrome,
// the first digit of the number also needs to be 0.
// Only 0 satisfy this property.
if(x < 0 || (x % 10 == 0 &&
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
// When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
// For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
// since the middle digit doesn''t matter in palidrome(it will always equal to itself), we can simply get rid of it.
return x == revertedNumber || x == revertedNumber/10;
}
判断回文字符串
提供一个判断回文字符串的方法:
bool isPalindrome__(const std::string& in)
{
std::string res = std::string(in.begin(),
std::mismatch(in.begin(), in.end(), in.rbegin()).first);
return in == res;
}
mismatch的实际算法源码如下,返回一个pair包括2个容器迭代器的位置:
template<class InputIt1, class InputIt2>
std::pair<InputIt1, InputIt2>
mismatch(InputIt1 first1, InputIt1 last1, InputIt2 first2)
{
while (first1 != last1 && *first1 == *first2) {
++first1, ++first2;
}
return std::make_pair(first1, first2);
}