[leetcode] 1680. Concatenation of Consecutive Binary Numbers

网友投稿 314 2022-08-27

[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 = 1Output: 1Explanation: "1" in binary corresponds to the decimal value 1.

Example 2:

Input: n = 3Output: 27Explanation: 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 = 12Output: 505379714Explanation: 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<

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

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<

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 91. Decode Ways
下一篇:python 实现桶排序
相关文章

 发表评论

暂时没有评论,来抢沙发吧~