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.
becomes
The illustration below explains the process of counting the digits in an integer.
n (value) | n | n/2 (Quotient) | n%2 (Remainder) |
---|---|---|---|
n is 125 |
125 | 62 | 1 |
n/2 becomes 62 |
62 | 31 | 0 |
n/2 becomes 31 |
31 | 15 | 1 |
n/2 becomes 15 |
15 | 7 | 1 |
n/2 becomes 7 |
7 | 3 | 1 |
n/2 becomes 3 |
3 | 1 | 1 |
n/2 becomes 1 |
1 | 0 | 1 |
Problem statement
Given an integer, return the number of bits present in an integer input.
Example #1:
Input: n = 125
Output: 7 (1, 1, 1, 1, 1, 0, 1)
Example #2:
Input: n = 129
Output: 8 (1, 0, 0, 0, 0, 0, 0, 1)
Approach #1: Bit-shifting
This is an example problem for converting from decimal to an integer. Solving this problem helps us to understand how bits are stacked together to form a decimal number. Let’s see some of the approaches to solve this algorithmic problem.
We used the right-shift operator here >>
. It divides the number ...