Skip to main content

Binary cheatsheet for coding interviews

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:

TechniqueCode
Test kth bit is setnum & (1 << k) != 0.
Set kth bitnum |= (1 << k)
Turn off kth bitnum &= ~(1 << k).
Toggle the kth bitnum ^= (1 << k).
Multiply by 2knum << k
Divide by 2knum >> k
Check if a number is a power of 2(num & num - 1) == 0 or (num & (-num)) == num
Swapping two variablesnum1 ^= num2; num2 ^= num1; num1 ^= num2

Essential questions

These are essential questions to practice if you're studying for this topic.

These are recommended questions to practice after you have studied for the topic and have practiced the essential questions.

AlgoMonster

AlgoMonster aims to help you ace the technical interview in the shortest time possible. By Google engineers, AlgoMonster uses a data-driven approach to teach you the most useful key question patterns and has contents to help you quickly revise basic data structures and algorithms. Best of all, AlgoMonster is not subscription-based - pay a one-time fee and get lifetime access. Join today for a 70% discount →

Grokking the Coding Interview: Patterns for Coding Questions

This course on by Design Gurus expands upon the questions on the recommended practice questions but approaches the practicing from a questions pattern perspective, which is an approach I also agree with for learning and have personally used to get better at coding interviews. The course allows you to practice selected questions in Java, Python, C++, JavaScript and also provides sample solutions in those languages along with step-by-step visualizations. Learn and understand patterns, not memorize answers! Get lifetime access now →

Master the Coding Interview: Data Structures + Algorithms

This Udemy bestseller is one of the highest-rated interview preparation course (4.6 stars, 21.5k ratings, 135k students) and packs 19 hours worth of contents into it. Like Tech Interview Handbook, it goes beyond coding interviews and covers resume, non-technical interviews, negotiations. It's an all-in-one package! Note that JavaScript is being used for the coding demos. Check it out →