难度:简单
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121 输出: true
示例 2:
输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10 输出: false 解释: 从右向左读, 为 01 。因此它不是一个回文数。
题目解析:
首先转换成字符串,使用双指针法进行首尾比对。
参考代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <unordered_map>
#include <cstring>
#include <map>
#include <stdexcept>
using namespace std;
class Solution {
public:
bool isPalindrome(int x) {
//负数的话是空的不对称的
if (x < 0)
return false;
string str = to_string(x);
int left = 0;
int right = str.size() - 1;
//使用双指针法进行比对
while (left < right)
{
if (str[left] != str[right])
return false;
++left;
--right;
}
return true;
}
};
int main()
{
Solution solution;
if (solution.isPalindrome(10))
cout << "yes" << endl;
else
cout << "no" << endl;
system("pause");
return 0;
}