↓Skip to main content
  1. LeetCode/

LeetCode 476: Number Complement

·1 min· ·
LeetCode Easy Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Wrong Answer → Accepted ×2

Approach
#

The complement flips only significant bits; plain ~num also flips the leading zeros and goes negative. mask = (1 << num.bit_length()) - 1 is all ones over num’s length, and num ^ mask is the answer (Bit Manipulation).

My Attempts
#

Attempt 1 used the example’s bin(5) and never switched to num, always returning 5’s complement, 2.

Solution
#

class Solution:
    def findComplement(self, num: int) -> int:
        return num ^ ((1 << num.bit_length()) - 1)

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • ~num flips every bit and yields a negative number.

Interview Explanation
#

The complement flips only significant bits, so I build an all-ones mask of num’s bit length and XOR. Time O(1).

Related

LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 461: Hamming Distance
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 461 note: each 1 in x ^ y is a differing bit, so count the ones