Find Bit Length of a Number
In this lesson, we make use of the Left Shift operator to find the bit length of a number.
We'll cover the following
Introduction
In this question, we take input and find its bit length.
Problem Statement
Given an input find its bit length.
Input: 8
Output: 4 (1000)
Input: 2
Output: 2 (10)
Input: 7
Output: 3 (111)
Algorithm
We already discussed the formula of the left shift operator.
a << b = ( a * )
Steps:
- Initialize a variable
bitsCounter
with value0
. - Now, left-shift
bitsCounter
until its values is less or equals to given number.- if true, increament the
bitsCounter
. on each iteration. - else, return
bitsCounter
.
- if true, increament the
Solution
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.