A palindrome number is a number that can be read the same way from left to right and from right to left. For example: 961169, 111, 554455 are palindromes, while 856, 10180, 7226 are not.
Find the largest palindrome number that satisfies the following rules:
- The number of its digits is equal to n, and must not contain leading zeros.
- The sum of its digits is equal to s.
If there is no such number print - 1.
InputThe first line of the input contains an integer T (1 ≤ T ≤ 500), where T is the number of the test cases.
Each test case has one line that contains two integers n (1 ≤ n ≤ 106) number of digits, and s (1 ≤ s ≤ 9 × 106) sum of digits.
OutputFor each test case, print a single integer that represents the largest palindrome number that satisfies the mentioned rules, if there is no such number print - 1.
Example
2 2 2 4 26
11
9449
这题的题目翻译过来的意思就是:
给定T 次数。 n数字位数 s每位数的和
一串数字的给定n,s 。 求是否存在,一个数字满足上面的要求,假若存在,则输出这个数,不存在则输出-1.
解题思路:
首先先要将不存在的情况分析出来(输出-1)
1.s大于n*9
2.n为偶数,s为奇数
3.n>1并且s等于1
除了这三种情况,都是存在数字满足上面要求。
我们再将,char a【】,全部赋值为‘9’-----> memset(a,'9',sizeof(a)); sum=9*n;
然后在分一次情况 n为奇数的时候。
mid=(1+n)/2
让a【mid】从‘9’慢慢减,直到到‘1’,对应是sum减1,满足sum==s的时候跳出循环
继续 a【mid-1】和a【n-mid+1】 继续执行自减,对应sum-=2;
直到满足sum==s
附上ac代码: (另外补一句,这里要用scanf和printf,不要用cin,cout,会超时间,我卡了很久的地方)
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int MAX=1e6+5;
char a[MAX];
int main()
{
int T;
scanf("%d",&T);//cin>>T;
while (T--){
int n,s,sum,i,j;
scanf("%d%d",&n,&s);//cin>>n>>s;
sum=n*9;
int mid=(n+1)/2;
for (i=1;i<=n;i++)
a[i]='9';
if ((n%2==0&&s%2==1)||sum<s||(n>1&&s==1)){
printf ("-1\n");//cout<<-1<<endl;
continue;
}
if (n%2==0){
for (;sum>s;){
a[mid]--;
a[n-mid+1]--;
sum-=2;
if (a[mid]=='0'){
mid--;
}
}
}
else if(n%2==1)
{
while (a[mid]>'0'&&sum>s){
sum--;
a[mid]--;
if (a[mid]=='1'&&s%2==1)
break;
}
for (mid--;sum>s;){ //
a[mid]--;
a[n-mid+1]--;
sum-=2;
if (a[mid]=='0'){
mid--;
}
}
}
for (i=1;i<=n;i++)
printf ("%c",a[i]);//cout<<a[i];
printf("\n");//cout<<endl;
}
return 0;
}