题解 | 小红的好数(数学方法)

小红的好数

https://www.nowcoder.com/practice/de234d0d61d549c6a436e9509dbeea11

仅需要事先计算好某一个数字放在第一位的满足条件数字共有几个即可,比如第一个数字如果是9,那么必然在前(9*8*7*6)个。把k的值减一,除以(9*8*7*6),就可以得到这个数字在9-0中排第几位。以此类推即可。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int k;
    cin >> k;
    k--;
    std::string str {""};
    vector<char> arr {'0','1','2','3','4','5','6','7','8','9'};
    std::reverse(arr.begin(),arr.end());
    for(int i = 1; i<=5; i++) {
        int num = 1;
        for(int step = 0; step<(5-i); step++) {
            num*= (10-i-step);
        }
        int span = k / num;
        // cout << span << endl;
        k = k % num;
        char c = '0';
        int cunt = 0;
        for(int j = 0; j<10; j++) {
            if(arr[j] != -1 && cunt++ == span)
            {
                c = arr[j];
                arr[j] = -1;
                break;
            }
        }
        str += c;
    }
    cout << str ;
}

全部评论

相关推荐

评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务