Find the absolute difference of set bits at even and odd indices of N
Given an integer N, the task is to find the absolute difference of set bits at even and odd indices of number N. (0-based Indexing)
Examples:
Input: N = 15
Output: 0
Explanation: The binary representation of 15 is 1111. So, it contains 1 on the 1st and 3rd position and it contains 1 on the 0th and 2nd position. Therefore, the difference between even and odd bits is 2 – 2 which is 0.Input: N = 17
Output: 2
Explanation: The binary representation of 17 is 10001. So, it contains 1 on the 0th and 4th positions. Therefore, the difference between even and odd bits is 2-0 which is 2.
Approach: This can be solved with the following idea:
Form a binary string of a given number N and start iterating from the right end, maintaining the sum of numbers present at even and odd indexes separately.
Below are the steps involved in the implementation of the code:
- Calculate the length of the binary representation of the number.
- Iterating through each bit position, checking if it is even or odd
- At last, Count the number of set bits accordingly using bitwise operations.
- Return the absolute difference between even and odd bits.
Below is the implementation of the code:
C++
// C++ implementation of code#include <bits/stdc++.h>using namespace std; // Function to find absolute differenceint diffEvenOddBit(int n){ int count1 = 0; int count2 = 0; int m = n; int len = 0; // Count the length of binary string while (m) { len++; m = m >> 1; } for (int i = 0; i < len; i++) { // Check for 1 at even index if (i % 2 == 0) { if (n & 1 << i) { count1++; } } // Check for 1 at odd index else { if (n & 1 << i) { count2++; } } } // Difference of even and odd bits int diff = count1 - count2; return diff;} // Driver codeint main(){ int n = 17; // Function call cout << diffEvenOddBit(n) << " "; return 0;} |
2
Time Complexity: O(logn)
Auxiliary Space: O(1)Related Articles:
Related Articles:



Please Login to comment...