LeetCode 1680 Concatenation of Consecutive Binary Numbers (Python)

Posted by 小明MaxMing on January 27, 2021

题目

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

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅