Friend Number II(简单思路题)

题目链接: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值