Digit Generator

来源:互联网 发布:51单片机与stm32 编辑:程序博客网 时间:2024/06/08 23:32

For a positive integer N, the digit-sum of N is defined as the sum of N itself and its digits. WhenM is the digitsum of N, we callN 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 of216 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 T is given in the first line of the input. Each test case takes one line containing an integerN, 1$ \le$N$ \le$100, 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 ofN for each test case. If N has multiple generators, print the smallest. IfN 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这道题使用一个数组将每个数对应的值保存下来,保存最小的,每次只要输出就行了,不过数组开大一点。
#include <stdio.h>const int maxn = 100005;int ans[maxn+505];int bit_sum ( int n ){    int sum = 0;    while ( n > 0 )    {        sum = sum+n%10;        n = n/10;    }    return sum;}int main ( ){    for ( int i = 1; i <= maxn; i ++ )    {        int s = i+bit_sum ( i );        if ( ans[s] == 0 )            ans[s] = i;    }    int T, n;    scanf ( "%d", &T );    while ( T -- )    {        scanf ( "%d", &n );        printf ( "%d\n", ans[n] );    }    return 0;}

 
0 0
原创粉丝点击