You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tech-interview-handbook/contents/algorithms/binary.md

1.5 KiB

id title
binary Binary

Notes

Questions involving binary representations and bitwise operations are asked sometimes and you must be absolutely familiar with how to convert a number from decimal form into binary form (and vice versa) in your chosen programming language.

Some helpful utility snippets:

  • Test kth bit is set: num & (1 << k) != 0.
  • Set kth bit: num |= (1 << k).
  • Turn off kth bit: num &= ~(1 << k).
  • Toggle the kth bit: num ^= (1 << k).
  • To check if a number is a power of 2, num & num - 1 == 0.

Corner cases

  • Be aware and check for overflow/underflow
  • Negative numbers

More questions

  • How do you verify if an integer is a power of 2?
  • Write a program to print the binary representation of an integer.
  • Write a program to print out the number of 1 bits in a given integer.
  • Write a program to determine the largest possible integer using the same number of 1 bits in a given number.