easy problem(思维+枚举)

easy problem

Description

给你一个数字N,N的范围是1~1000000,求一个最小的正整数M,这个数字M的各个位的数字加上它本身之和恰好为N。当然,如果没有解,输出0。

Input

输入数据由多组数据组成,每行由一个数字N组成(1<=N<=1000000)。

Output

对于每组数据,输出仅一行包含一个整数M。如果对于每个N,存在最小的M,则输出这个最小值。如果不存在这个最小的M,则输出0。

Sample Input 1 

216 
121 
2005

Sample Output 1

198
0
1979

思路:设各个位数之和为sum,则sum最大是54(6个9),最小是1。遍历sum1~54,判断(n-sum)的各个位数之和是不是sum,如果是则符合题意,输出n

#include<cstdio>
using namespace std;
int main(){
	int n;
	while(~scanf("%d",&n)){
		bool flag=false;
		for(int i=54;i>0;i--){ //i为各位数之和 
			int m=n-i;
			if(m<=0) continue;
			int a=0,b=m;
			while(b){
				a+=b%10;
				b/=10;
			} 
			if(a==i){
				printf("%d\n",m);
				flag=true;
				break;
			}
		}
		if(!flag) printf("0\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42936517/article/details/86560929