Concept for Binary questions

Concept for Binary questions

Concept for Binary questions

This is about Leetcode

https://leetcode.com/problems/number-complement/description/?envType=daily-question&envId=2024-08-22

Difficulty as easy, however, it concept is not.

Question: provide a number, return its complement,

for example, a 5 is 101 in binary, reverse 0/1 to 010, so return 2

Solution:

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

There’s some crucial steps inside

  • we need the bit wise length of given number, will use later. (num.bit_length() )
  • “<<” is a left shift operator, 1<<n means we shift 1 n times to left, for example, if 1<<2 then we’ll get 100
  • -1 means whenever the number we got, we minus 1, in previous example 100 (4) minus 1 is 11(3)
  • Now if we perform a XOR (^) with original number, because 1^0 or 0 ^1 will be 1, and 1 ^1 or 0 ^0 will be 0, with a mask of all 1, we can now filp the number.

Comments

Loading comments…

Leave a Comment