1680. Concatenation of Consecutive Binary Numbers

Source: https://leetcode.com/contest/weekly-contest-218/problems/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 10^9 + 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

思路:递推
f ( n ) f(n) f(n)表示1至n的二进制表示连起来的值,则 f ( n ) = ( f ( n − 1 ) < < n 的 位 数 ) + n f(n)=(f(n-1)<<n的位数)+n f(n)=(f(n1)<<n)+n

求一个数的二进制表示里1的个数可以用内置函数__builtiin_popcount()

但是计算数的二进制表示的位数只能自己写了(以下为计算1至n的二进制表示的位数)

O ( n lg ⁡ n ) O(n\lg n) O(nlgn)的方式:

int get_len(int x){
	    int res=0;
        while(x){
            res++,x>>=1;
        }
        return res;
    }

O ( n ) O(n) O(n)的方式(递推):

vector<int> dig(n+1);
for(int i=1;i<=n;i++){
    dig[i]=dig[i/2]+1;
}

所以这题的代码是

class Solution {
public:
    const int mod=1e9+7;    
    typedef long long ll;
    int concatenatedBinary(int n) {
        vector<int> dig(n+1);
        dig[1]=1;
        int ans=0;
        for(int i=1;i<=n;i++){
            dig[i]=dig[i/2]+1;
            ans=(i+((ll)ans<<dig[i]))%mod;
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值