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/)