Bitwise Operators: Bitwise AND of all even number from 1 to N

Problem Statement:

You are given a number N, you need to perform bitwise AND on all the even numbers.

Example:

Input: 2 
Output: 2

Solution 1:

Starting from 2, iterate from 4 to n and do the bitwise AND.

Time Complexity: O(n)
Space Complexity: O(1)

Solution 2:

In this approach, if n is less than 4, then return 2.

Return 0 for all N >= 4, because bitwise AND of 2 and 4 is 0, hence the value is 0.

Time Complexity: O(1)
Space Complexity: O(1)

Code Solution


#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int solution_1(int n)
{
    int result = 2;
 
    for (int i = 4; i <= n; i = i + 2) 
    {
        result = result & i;
    }
    return result;
}

int solution_2(int n)
{
    if (n < 4)
        return 2;
    else
        return 0;
}
 
int main()
{
    int n = 2;
    cout << solution_1(n)<<endl;
    cout << solution_2(n);
    return 0;
}

Output

2
2
Write a Comment

Leave a Comment

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