【白书之路】1583 - Digit Generator

1583 - Digit Generator

For a positive integer N , the digit-sum of N is defined as the sum of N itself and its digits. When M is the digitsum of N , we call N a generator of M .

For example, the digit-sum of 245 is 256 (= 245 + 2 + 4 + 5). Therefore, 245 is a generator of 256.

Not surprisingly, some numbers do not have any generators and some numbers have more than one generator. For example, the generators of 216 are 198 and 207.

You are to write a program to find the smallest generator of the given integer.

Input


Your program is to read from standard input. The input consists of T test cases. The number of test cases Tis given in the first line of the input. Each test case takes one line containing an integer N , 1N100, 000 .

Output


Your program is to write to standard output. Print exactly one line for each test case. The line is to contain a generator of N for each test case. If N has multiple generators, print the smallest. If N does not have any generators, print 0.

The following shows sample input and output for three test cases.

Sample Input


3 
216 
121 
2005

Sample Output


198 
0 
1979

我们设置一个函数ds(N)用来求整数N的digit_sum,如果ds(N)=M,那么N就是M的generator,这是首先需要明确的。

因为digit_sum的求法是本身加上每一位之和,那么我们容易得出,如果一个数n有t位,那么每一位之和s最大就是9*t,他的generator最小就是n-9*t,再小的话永远也不可能达到这个数了;而最大也不能大于这个数。

找到了范围,我们就可以在这个范围内枚举比较,从而找出要求的数。

#include <iostream>
#include <stdio.h>
using namespace std;

int get_range(int num)//计算一个数有几位
{
    int i;
    for(i=0;num!=0;i++)
        num/=10;
    return i;
}

int cal(int num)//计算digit_sum
{
    int sum=num;
    while(num!=0)
    {
        sum+=num%10;
        num/=10;
    }
    return sum;
}

int get_generator(int num,int range)//计算最小的generator
{
    range*=9;
    for(int i=num-range;i<num;i++)
    {
        if(cal(i)==num)
            return i;
    }
    return 0;
}


int main()
{
    int num,res,t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&num);
        res=get_generator(num,get_range(num));
        printf("%d\n",res);
    }
    return 0;
}



你可能感兴趣的:(generator,digit,白书之路,1583)