[leetcode] 1680. Concatenation of Consecutive Binary Numbers

Description

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 <= 105

分析

题目的意思是:给定一个数n,求出把1~n表示成二进制然后拼接一起的数。这道题把它转换成10进制来做,首先要确定对于数i,需要把数向左移动的长度,这里用base,当i&(i-1)==0的时候,说明移动的长度base要更新了,更新base了之后再进行计算。
比如:
``
1 1
2 10
3 11
4 100
5 101

其中遍历到2,4,8...的时候需要更新向左移动的长度,即需要更新base了。res的计算为:

res=((res<<base)+i)%mod

为避免数过大,需要进行取余操作

## 代码

class Solution:
def concatenatedBinary(self, n: int) -> int:
mod=10**9+7
base=0
res=0
for i in range(1,n+1):
if(i&(i-1)==0):
base+=1
res=((res<<base)+i)%mod
return res

## 参考文献
[连接连续二进制数字](https://leetcode-cn.com/problems/concatenation-of-consecutive-binary-numbers/solution/lian-jie-lian-xu-er-jin-zhi-shu-zi-by-ze-t40j/)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值