Codeforces Round #690 (Div. 3) C. Unique Number 常规解法

原题

You are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique).

Input
The first line contains a single positive integer t (1≤t≤50) — the number of test cases in the test. Then t test cases follow.

Each test case consists of a single integer number x (1≤x≤50).

Output
Output t answers to the test cases:

  • if a positive integer number with the sum of digits equal to x and all digits are different exists, print the smallest such number;
  • otherwise print -1.

Input
4
1
5
15
50

Output
1
5
69
-1


题目概述

给你一个数n(n <= 50),让你找一个最小的数x,其每一位的数各不相同且相加等于n,若不存在则输出-1。

简单的解释
  • 既然x的每一位的数都不相同,也就是说x最多就只有9位,即123456789,累加得到n=45,即n>45时,必定为-1。
  • 由于让你找最小的一个数,也就是说其各位数要尽量大,也就是说只要n>9.则x的个位必然为9。
  • 以此类推,便可以从i=9→1枚举,使x-=i。当x<i时,i=x。
  • 最后每进行一步便将数值i标记出来。
程序如下
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
const int N = 1e4+10;
 
using namespace std;
 
int main(){
	int n;
	cin >> n;
	for(int i = 0;i < n;i++){
		int x;
		cin >> x;
		if(x > 45){        //x>45必然为-1
			cout << "-1" << endl;
			continue;
		}
		int a[10];memset(a,0,sizeof(a)); //这里用数组标记数字,实际上写麻烦了
		for(int i = 9;i >= 1;i--){   //从9开始
			if(x < i){    //最后一步的时候必然x<i
				a[x] = 1;break;
			}
			x -= i;a[i] = 1; //符合条件的标记出来
		}
		for(int i = 1;i < 10;i++){
			if(a[i])cout << i;
		}
		cout << endl;
	}
	return 0;
	}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值