Find the remainder when N is divided by 4 using Bitwise AND operator
Given a number N, the task is to find the remainder when N is divided by 4 using Bitwise AND operator.
Input: N = 98 Output: 2 Explanation: 98 % 4 = 2. Hence the output is 2. Input: 200 Output: 0 Explanation: 200 % 4 = 0. Hence output is 0.
For solving the above-mentioned problem we can use a naive method by using the Modulo (%) operator to find the remainder. But, the Modulo operator is computationally expensive and the method is inefficient.
If we carefully observe the binary representation of N and its remainder with 4, we observe that remainder is simply the rightmost two bits in N. To get the rightmost two bits in number N, we perform bitwise AND (&) with 3 because 3 in binary is 0011. To understand the approach better let us have a look at the image below:
Below is the implementation of the above approach:
Time Complexity: O(1)
Attention reader! Don’t stop learning now. Join the First-Step-to-DSA Course for Class 9 to 12 students , specifically designed to introduce data structures and algorithms to the class 9 to 12 students