LeetCode: 902. Numbers At Most N Given Digit Set

LeetCode: 902. Numbers At Most N Given Digit Set

题目描述

We have a sorted set of digits D, a non-empty subset of {'1','2','3','4','5','6','7','8','9'}. (Note that '0' is not included.)

Now, we write numbers using these digits, using each digit as many times as we want. For example, if D = {'1','3','5'}, we may write numbers such as '13', '551', '1351315'.

Return the number of positive integers that can be written (using the digits of D) that are less than or equal to N.

Example 1:

Input: D = ["1","3","5","7"], N = 100
Output: 20
Explanation: 
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.

Example 2:

Input: D = ["1","4","9"], N = 1000000000
Output: 29523
Explanation: 
We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
In total, this is 29523 integers that can be written using the digits of D.

Note:

D is a subset of digits '1'-'9' in sorted order.
1 <= N <= 10^9

解题思路

小于 N 的数的数量等于位数小于 N 的数(一定 比 N 小)和位数和 N 一样的小于等于N的数的数量和。

AC 代码

class Solution {
public:
    int atMostNGivenDigitSet(vector<string>& D, int N, bool flag = false) {
        int count = 0;
        string num = to_string(N);

        // 位数小于 N 的一定 比 N 小
        for(int i = 1; !flag && i < num.size(); ++i)
        {
            count += pow(D.size(), i);
        }

        // 位数和 N 一样的
        for(int i = 0; i < D.size(); ++i)
        {
            if(num[0] > D[i][0]) // 第一位小于 N
            {
                count += pow(D.size(), num.size()-1); 
            }
            else if(num[0] == D[i][0]) //第一位等于 N
            {
                string subNum = num.substr(1, num.size());
                if(subNum.empty()) { ++count; continue; }
                else if(subNum[0] == '0') continue; // 首数字为 0
                count += atMostNGivenDigitSet(D, stoi(subNum), true); 
            }
        }

        return count;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-24 20:55
阿里国际 Java工程师 2.7k*16.0
程序员猪皮:没有超过3k的,不太好选。春招再看看
点赞 评论 收藏
分享
11-11 14:21
西京学院 C++
无敌混子大王:首先一点,不管学校层次怎么样,教育经历放在第一页靠上位置,第一页看不到教育经历,hr基本直接扔掉了
点赞 评论 收藏
分享
专心打鱼:互联网搬运工,贴子都要偷
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务