题目链接:Friend Number II
Given a positive integer x, let S(x) denotes the sum of all x’s digits. Two integers x and y are friend numbers if S(x)=S(y). Here comes the problem: Given a positive integer x, of course it has a lot of friend numbers, find the smallest one which is greater than x,please.
Input
There are multiple test cases. The first line of input is an integer T (0
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<string>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f3f3f3f3f
const int maxn=2009;
#define mem(aa,bb) memset(aa,bb,sizeof(aa))
#define PI acos(-1.0)
int cun[maxn];
char a[maxn];
int main()
{
int len;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",a+1);
int la=strlen(a+1);
len=0;
a[0]='0';//加一个前导零
int i;
for(i=la; i>=1&&a[i]=='0'; i--)//把0都放入数组,等待排序
cun[len++]=0;
if(a[i-1]!='9')//如果i-1位不是9
{
for(int j=1; j<i-1; j++)
printf("%c",a[j]);
printf("%d",(a[i-1]-'0')+1);
cun[len++]=(a[i]-'0');
}
else//如果是9
{
for(; i>0; i--)//找第一个不是9的数字
{
if(a[i-1]!='9'&&a[i]=='9')
{
a[i-1]=((a[i-1]-'0')+1)+'0';
cun[len++]=(a[i]-'0');
break;
}
else cun[len++]=a[i]-'0';
}
if(a[0]!='0')//如果找到了前导零的位置
printf("%c",a[0]);
for(int j=1; j<i; j++)
printf("%c",a[j]);
}
sort(cun,cun+len);//从小到大排序
int flag=1;
for(int j=0; j<len; j++)
if(flag&&cun[j]!=0)
printf("%d",cun[j]-1),flag=0;//因为上面加一了,所以这里要减一
else printf("%d",cun[j]);
printf("\n");
}
return 0;
}