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:

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

 

Approach #1: Math. [C++]

class Solution {
public:
    int atMostNGivenDigitSet(vector<string>& D, int N) {
        string s = to_string(N);
        int n = s.length();
        int ans = 0;
        for (int i = 1; i < n; ++i) 
            ans += pow(D.size(), i);
        for (int i = 0; i < n; ++i) {
            bool prefix = false;
            for (string d : D) {
                if (d[0] < s[i]) {
                    ans += pow(D.size(), n-i-1);
                } else if (d[0] == s[i]) {
                    prefix = true;
                    break;
                }
            }
            
            if (!prefix) return ans;
        }
        
        return ans + 1;
    }
};

  

 

Reference:

https://zxi.mytechroad.com/blog/math/leetcode-902-numbers-at-most-n-given-digit-set/

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/10592258.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值