题目
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.
解题思路
遍历1到n,每次左移i的位数,并加i,之后取mod
代码
class Solution:
def concatenatedBinary(self, n: int) -> int:
bits, res, MOD = 1, 0, 10**9 + 7
for x in range(1, n + 1):
res = ((res << bits) + x) % MOD
if x == (1 << bits) - 1:
bits += 1
return res