
- 这道题当时老是想着固定最外面的两个数,里边的呈周期状态。边界条件很多,上下取整考虑不周,写出了很臃肿的代码
#include<iostream>
#include<algorithm>
#include<map>
#include<stdio.h>
#include<string.h>
#include<unordered_map>
#include<vector>
#include<queue>
#include<set>
#include<math.h>
using namespace std;
const int mod = 998244353;
typedef long long ll;
class Solution {
public:
vector<long long> kthPalindrome(vector<int>& queries, int intLength) {
vector<long long> ans;
for(int i = 0;i<queries.size();i++)
{
if(intLength == 1) {
if(queries[i]>=1&&queries[i]<=9) ans.push_back(queries[i]);
else ans.push_back(-1);
continue;
}
int a = queries[i];
int len = intLength;
bool flag = true;
vector<int> ao; bool first = true;
while(len >= 2)
{
int o_1 = (int)ceil((double)(len - 2)/2);
int o=(int)pow(10,o_1);
int m=(int)ceil((double)((double)a / o));
if(first && !(m>=1 && m<=9)) {flag = false;break;}
if(!first && !(m>=1 && m<=10)) {flag=false;break;}
if(first) ao.push_back(m); else ao.push_back(m-1);
first = false;
len-=2;
a-=(m-1)*o;
}
int temp[intLength];
if(len == 1) {if(a>=1 && a<=10) {ao.push_back(a-1);} else flag = false;}
if(flag) {
int i =0 ,j = intLength - 1,k=0;
while(i<=j)
{
temp[i] = temp[j] = ao[k++];
i++; j--;
}
long long t = 0;
for(i = intLength- 1;i>=0;i--) t = t*10 + (long long)temp[i];
ans.push_back(t);
}
else ans.push_back(-1);
}
return ans;
}
};
- 换一种思路:
- 回文数前后是相反关系,第几大的数仅仅取决于前面部分而不取决于后面部分
- 不要拘泥于回文数的构造
class Solution {
public:
vector<long long> kthPalindrome(vector<int>& queries, int intLength) {
vector<long long> ans;
for(int i = 0;i<queries.size();i++)
{
int a = queries[i];
int b = (intLength - 1)/ 2;
long long l = 1;
for(int j = 0;j<b;j++) l*=10;
int highest = (long long)(a - 1)/l+1;
if(intLength == 1 && (highest >= 0 && highest <= 9))
{
ans.push_back(highest);
continue;
}
if(!(1 <= highest && highest <= 9)) ans.push_back(-1);
else
{
a -= (highest - 1) * l;
a--;
long long ans_1 = highest;
ans_1*=l; ans_1+=(long long)a;
if(intLength % 2) {a/=10;b--;}
while(b>0)
{
ans_1 = ans_1 * 10 + a % 10;
a/=10;
b--;
}
ans_1 = ans_1 * 10 + highest;
ans.push_back(ans_1);
}
}
return ans;
}
};