LeetCode: 878. Nth Magical Number

LeetCode: 878. Nth Magical Number

题目描述

A positive integer is magical if it is divisible by either A or B.

Return the N-th magical number. Since the answer may be very large, return it modulo 10^9 + 7.

Example 1:

Input: N = 1, A = 2, B = 3
Output: 2

Example 2:

Input: N = 4, A = 2, B = 3
Output: 6

Example 3:

Input: N = 5, A = 2, B = 4
Output: 10

Example 4:

Input: N = 3, A = 6, B = 4
Output: 8

Note:

1 <= N <= 10^9
2 <= A <= 40000
2 <= B <= 40000

解题思路

枚举 A*B 之前所有可能的组合情况, 然后根据 N 与它的关系,计算第 N 个数。

AC 代码

class Solution {

public:
    int nthMagicalNumber(int N, int A, int B) {

        set<long long int> AB;
        for(int i = 1; i <= B; ++i)
        {
            AB.insert(A*i);
        }
        for(int i = 1; i <= A; ++i)
        {
            AB.insert(B*i);
        }

        int t = N / AB.size();
        int c = N % AB.size();

        long long int ans = 0;
        while(t--)
        {
            ans += (*AB.rbegin());
            ans %= 1000000007;
        }
        cout << c << endl;

        auto iter = AB.begin();
        if(c){
            while(--c) ++iter;
            ans += (*iter);
            ans =ans % 1000000007;
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值