Bitwise Operators: Toggle all even bits of a number

Problem Statement:

You are given a number, toggle all even bit of the number.

Example:

Input: 10

Output: 0

10 in binary 1010
After toggle 0000

Solution 1:

Generate a number that contains even position bits.

Then take XOR with the original number.

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

Code Solution

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

using namespace std;

int solution(int n)
{

    int result = 0;
    int count = 0;
    for (int temp = n; temp > 0; temp >>= 1) 
    {
 
        if (count % 2 == 1)
            result |= (1 << count);      
 
        count++;
    }
 
    return n ^ result;
}
 
int main()
{
    int n = 10;
    cout << solution(n);
    return 0;
}

Output

0
Write a Comment

Leave a Comment

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