LeetCode 题解工作台

负二进制转换

给你一个整数 n ,以二进制字符串的形式返回该整数的 负二进制( base -2 ) 表示。 注意, 除非字符串就是 "0" ,否则返回的字符串中不能含有前导零。 示例 1: 输入: n = 2 输出: "110" 解释: (-2) 2 + (-2) 1 = 2 示例 2: 输入: n = 3 输出…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·driven

bolt

答案摘要

我们可以判断 从低位到高位的每一位,如果该位为 ,那么答案的该位为 ,否则为 。如果该位为 ,那么我们需要将 减去 。接下来我们更新 $n = \lfloor n / 2 \rfloor$, $k = -k$。继续判断下一位。 最后,我们将答案反转后返回即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 n ,以二进制字符串的形式返回该整数的 负二进制(base -2表示。

注意,除非字符串就是 "0",否则返回的字符串中不能含有前导零。

 

示例 1:

输入:n = 2
输出:"110"
解释:(-2)2 + (-2)1 = 2

示例 2:

输入:n = 3
输出:"111"
解释:(-2)2 + (-2)1 + (-2)0 = 3

示例 3:

输入:n = 4
输出:"100"
解释:(-2)2 = 4

 

提示:

  • 0 <= n <= 109
lightbulb

解题思路

方法一:模拟

我们可以判断 nn 从低位到高位的每一位,如果该位为 11,那么答案的该位为 11,否则为 00。如果该位为 11,那么我们需要将 nn 减去 kk。接下来我们更新 n=n/2n = \lfloor n / 2 \rfloor, k=kk = -k。继续判断下一位。

最后,我们将答案反转后返回即可。

时间复杂度 O(logn)O(\log n),其中 nn 为给定的整数。忽略答案的空间消耗,空间复杂度 O(1)O(1)

相似题目:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def baseNeg2(self, n: int) -> str:
        k = 1
        ans = []
        while n:
            if n % 2:
                ans.append('1')
                n -= k
            else:
                ans.append('0')
            n //= 2
            k *= -1
        return ''.join(ans[::-1]) or '0'
speed

复杂度分析

指标
时间complexity is O(log n) because each division reduces n roughly by a factor of 2. Space complexity is O(log n) to store the resulting digits in the output string.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Are you tracking how negative remainders affect digit placement?

  • question_mark

    How do you handle normalization of digits when division yields negative remainders?

  • question_mark

    Can you produce a result string without leading zeros efficiently?

warning

常见陷阱

外企场景
  • error

    Forgetting to adjust negative remainders leads to incorrect digit sequences.

  • error

    Appending digits in the wrong order without reversing at the end.

  • error

    Returning strings with unnecessary leading zeros instead of minimal length.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Convert numbers to other negative bases like -3 or -5 using the same remainder adjustment strategy.

  • arrow_right_alt

    Output the base -2 digits as an array of integers instead of a string.

  • arrow_right_alt

    Handle signed integers including negative numbers in base -2 representation.

help

常见问题

外企场景

负二进制转换题解:数学·driven | LeetCode #1017 中等