1680. Concatenation of Consecutive Binary Numbers

题目:

Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.

 

Example 1:

Input: n = 1
Output: 1
Explanation: "1" in binary corresponds to the decimal value 1. 

Example 2:

Input: n = 3
Output: 27
Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
After concatenating them, we have "11011", which corresponds to the decimal value 27.

Example 3:

Input: n = 12
Output: 505379714
Explanation: The concatenation results in "1101110010111011110001001101010111100".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.

 

Constraints:

  • 1 <= n <= 10^5

 

 

思路:

首先如果是真的按照思路走用字符串拼接的话肯定会超时,因为数据规模在10^5,只能O(n)或者更小。

根据观察得出规律:

n=1, f(1)=1

n=2, f(2)=[f(1) << 2] + 2 = 6

n=3, f(3)=[f(2) << 2] + 3 = 27

n=4, f(4)=[f(3) << 3] + 4 = 220

可以看出左移的位数和n的位数是相同的。

因此手动计算当前n的位数,然后进行左移和加n,中间不要忘记取模。另外因为数值过大,最初的记录答案的类型可以为long long。

 

 

代码:

class Solution {
public:
    int concatenatedBinary(int n) {
        int mode =1e9+7;
        long long ans=1;
        for(int i=2;i<=n;i++)
        {
            ans=ans<<count(i);
            ans%=mode;
            ans+=i;
            ans%=mode;
        }
        return ans;
    }
    
private:
    int count(int n)
    {
        int ans=0;
        while(n>0)
        {
            ans++;
            n=n>>1;
        }
        return ans;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值