zoukankan      html  css  js  c++  java
  • [编程题]多多的数字组合

    牛客网拼多多面试题:

    多多君最近在研究某种数字组合:
    定义为:每个数字的十进制表示中(0~9),每个数位各不相同且各个数位之和等于N。
    满足条件的数字可能很多,找到其中的最小值即可。
    多多君还有很多研究课题,于是多多君找到了你--未来的计算机科学家寻求帮助。


    输入描述:
    共一行,一个正整数N,如题意所示,表示组合中数字不同数位之和。
    (1 <= N <= 1,000)

    输出描述:
    共一行,一个整数,表示该组合中的最小值。
    如果组合中没有任何符合条件的数字,那么输出-1即可。

    输入例子1:
    5

    输出例子1:
    5

    例子说明1:
    符合条件的数字有:5,14,23,32,41
    其中最小值为5

    输入例子2:
    12

    输出例子2:
    39

    例子说明2:
    
    
    输入例子3:
    50

    输出例子3:
    -1

    例子说明3:
    没有符合条件的数字 (T▽T)

    -------------------------


    解析:题目45以下就会有重复即1+2+3+4+5+6+7+8+9;保证最小即按照最大在低位进行计算。
    代码如下:
    #include<cstdio>
    #include<cmath>
    #include<cstring>
    #include<algorithm>
    #include<map>
    using namespace std;
    
    int main() {
        int n;
        scanf("%d", &n);
        if (n > 45) {
            printf("-1
    ");
            return 0;
        }
    
        int ans[20], cnt = 0, pp = 9;
        map<int, int> mp;
    
        while(n != 0) {
            if (mp[pp] == 0 && n >= pp) {
                ans[cnt] = pp;
                mp[pp] = 1;
                n = n - pp;
                cnt++;
            } 
            pp--;
        }
    
        for (int i = cnt-1; i >= 0; i--) {
            printf("%d", ans[i]);
        }
        printf("
    ");
    
        return 0;
    }
  • 相关阅读:
    设计模式之命令模式
    设计模式之访问者模式
    ES6入门之Generator函数
    ES6入门之Iterator和for...of
    c# TcpClient简易聊天工具
    Mvc Action可以通过jsonp方式调取
    Webbrowser 在web项目中的使用
    关于java post get请求Demo (请求c#iis接口)
    Jquery 引擎模板 -template详解
    Redis在windows下安装过程
  • 原文地址:https://www.cnblogs.com/smuzoey/p/14778498.html
Copyright © 2011-2022 走看看