Divide and Multiply a number by Two using Bitwise Operator (Without ‘*’, ‘/’)

Divide and Multiply a number by Two using Bitwise Operator (Without ‘*’, ‘/’)

Why use left-shift and right-shift operators instead of generic divide(/) and multiply(*) operators? 

Explanation:

The ‘/’ and ‘*’ operators can be very time-consuming especially in solving coding contests or competitive programming questions. So to boost up the performance of your code use left-shift (<<) and right-shift (>>) operators.

Multiply by Two using Left Shift Operator

Example:

12 * 2 = 12 << 1
17 * 2 = 17 << 1

C++ Code:

#include <iostream>
using namespace std;
 
int main()
{
   //number is 16
   int num = 16;

   int res = num<<1;
   cout<<"Origional number: "<<num<<endl;
   cout<<"Multiply by two: "<<res<<endl;

   return 0;
}

Output:

Origional number: 16 
Multiply by two: 32

Divide by Two using Right Shift Operator

Example:

12/2 = 12>>1 
17/2 = 17>>1

C++ Code:

#include <iostream>
using namespace std;
 
int main()
{
   //number is 16
   int num = 16;

   int res = num>>1;

   cout<<"Origional number: "<<num<<endl;
   cout<<"Divide by two: "<<res<<endl;
   return 0;
}

Output:

Origional number: 16 
Divide by two: 8

Just like the left and right shift operator, you can use the logical AND operator to check whether the given number is odd or even.

This is a very simple trick to divide and multiply a number by two using bitwise operator. To know more about such simple and powerful bitwise operations, check the bitwise coding question list in the data structure and coding questions.

All the best!

Leave a Reply

Your email address will not be published. Required fields are marked *