力扣9. 回文数
https://leetcode-cn.com/problems/palindrome-number/
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
我的答案:
复杂度分析
时间复杂度:O(log10(n)),对于每次迭代,我们会将输入除以10,因此时间复杂度为 O(log 10(n))。
空间复杂度:O(1)。
#include "stdafx.h"
#include <vector>
#include<math.h>
using namespace std;
class Solution
{
public:
bool isPalindrome(int x)
{
if (x<0)
{
return false;
}
//得到位数
int x1 = x;
int j=0;
while (x1)
{
x1 = x1 / 10;
j++;
}
//将每一位数存进vector
int x2 = x;
int j1 = j;
vector<int>vec;
while (j1!=0)
{
vec.push_back(((x2 / (int)pow(10, j1-1)) % 10));
j1--;
}
//通过vector比较,一前一后比较
int i = 0;
int j3 = j - 1;
while (i<j3)
{
if (vec[i]!= vec[j3])
{
return false;
}
i++;
j3--;
}
return true;
}
};
int main()
{
Solution s;
auto result = s.isPalindrome(123621);
return 0;
}