Convert Decimal Number to Binary Number

In this lesson, we will write the code to count the number of bits present for a given input.

Introduction

Given a decimal number, continue dividing the number by 2 until it reaches either 0/1 and record the remainder at each step. The resulting list of remainders is the equivalent binary number for your decimal number.

For example:

Input: 125

Output: 1111101

Repeatedly do the modulo operation until n becomes 0 using

%” and “division” operations.

So, using the modulo and division method, we calculate the binary representation of a decimal number. Let’s represent the binary by considering the remainder column from bottom to top.

(125)10(125)_{10} becomes (1111101)2(1111101)_{2}

The illustration below explains the process of counting the digits in an integer.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.