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

2.3 KiB

id title toc_max_heading_level
binary Binary 2

Introduction

Knowledge of binary number system and bit manipulation is less important in coding interviews as most Software Engineers do not have to deal with bits, which is more commonly used when dealing with lower level systems and programming languages. They are still asked sometimes, so you should at least still know how to convert a number from decimal form into binary form, and vice versa, in your chosen programming language.

Learning resources

Corner cases

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

Techniques

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:

Technique Code
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).
Multiple by 2k num << k
Divide by 2k num >> k
Check if a number is a power of 2 (num & num - 1) == 0 or (num & (-num)) == num
Swapping two variables num1 ^= num2; num2 ^= num1; num1 ^= num2

import AlgorithmCourses from '../_courses/AlgorithmCourses.md'