LeetCode 题解工作台

连接连续二进制数字

给你一个整数 n ,请你将 1 到 n 的二进制表示连接起来,并返回连接结果对应的 十进制 数字对 10 9 + 7 取余的结果。 示例 1: 输入: n = 1 输出: 1 解释: 二进制的 "1" 对应着十进制的 1 。 示例 2: 输入: n = 3 输出: 27 解释: 二进制下,1,2 和…

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·位运算

bolt

答案摘要

观察数字的连接规律,我们可以发现,当连接到第 个数时,实际上是将前 个数连接而成的结果 往左移动一定的位数,然后再加上 这个数,移动的位数是 中二进制的位数。 时间复杂度 ,其中 为给定的整数。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·位运算 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 n ,请你将 1 到 n 的二进制表示连接起来,并返回连接结果对应的 十进制 数字对 109 + 7 取余的结果。

 

示例 1:

输入:n = 1
输出:1
解释:二进制的 "1" 对应着十进制的 1 。

示例 2:

输入:n = 3
输出:27
解释:二进制下,1,2 和 3 分别对应 "1" ,"10" 和 "11" 。
将它们依次连接,我们得到 "11011" ,对应着十进制的 27 。

示例 3:

输入:n = 12
输出:505379714
解释:连接结果为 "1101110010111011110001001101010111100" 。
对应的十进制数字为 118505380540 。
对 109 + 7 取余后,结果为 505379714 。

 

提示:

  • 1 <= n <= 105
lightbulb

解题思路

方法一:位运算

观察数字的连接规律,我们可以发现,当连接到第 ii 个数时,实际上是将前 i1i-1 个数连接而成的结果 ansans 往左移动一定的位数,然后再加上 ii 这个数,移动的位数是 ii 中二进制的位数。

时间复杂度 O(n)O(n),其中 nn 为给定的整数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def concatenatedBinary(self, n: int) -> int:
        mod = 10**9 + 7
        ans = 0
        for i in range(1, n + 1):
            ans = (ans << i.bit_length() | i) % mod
        return ans
speed

复杂度分析

指标
时间complexity is O(n) since each number requires a constant-time shift and addition with modulo. Space complexity is O(1) as no extra arrays or strings are stored, only the running result and temporary variables.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate immediately recognizes the problem as math plus bit manipulation with shifting and modulo.

  • question_mark

    Candidate attempts naive string concatenation and is prompted to optimize using numeric shifts.

  • question_mark

    Candidate considers overflow and applies modulo iteratively to maintain correctness.

warning

常见陷阱

外企场景
  • error

    Trying to concatenate actual binary strings leads to memory inefficiency and TLE for large n.

  • error

    Forgetting to shift the result by the correct bit length of the current number causes incorrect decimal values.

  • error

    Neglecting modulo at each step results in integer overflow and wrong answers for large n.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the concatenation in hexadecimal instead of decimal, still using bit manipulation to compute efficiently.

  • arrow_right_alt

    Calculate the sum of the decimal values of all prefixes of the concatenated binary string.

  • arrow_right_alt

    Compute the concatenation modulo a different prime, emphasizing modular arithmetic properties.

help

常见问题

外企场景

连接连续二进制数字题解:数学·位运算 | LeetCode #1680 中等