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.

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 * 2b2^{b} )

Steps:

  • Initialize a variable bitsCounter with value 0.
  • 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.

Solution

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