# Discover absolutely the distinction of set bits at even and odd indices of N

Given an integer N, the duty is to seek out absolutely the distinction of set bits at even and odd indices of quantity N. (0-based Indexing)

Examples:

Enter: N = 15
Output: 0
Clarification: The binary illustration of 15 is 1111. So, it comprises 1 on the first and third place and it comprises 1 on the 0th and 2nd place. Subsequently, the distinction between even and odd bits is 2 – 2 which is 0.

Enter: N = 17
Output: 2
Clarification: The binary illustration of 17 is 10001. So, it comprises 1 on the 0th and 4th positions. Subsequently, the distinction between even and odd bits is 2-0 which is 2.

Method: This may be solved with the next concept:

Type a binary string of a given quantity N and begin iterating from the suitable finish, sustaining the sum of numbers current at even and odd indexes individually.

Beneath are the steps concerned within the implementation of the code:

• Calculate the size of the binary illustration of the quantity.
• Iterating by way of every bit place, checking whether it is even or odd
• Eventually, Rely the variety of set bits accordingly utilizing bitwise operations.
• Return absolutely the distinction between even and odd bits.

Beneath is the implementation of the code:

## C++

 `#embrace ` `utilizing` `namespace` `std;` ` `  `int` `diffEvenOddBit(``int` `n)` `{` ` `  `    ``int` `count1 = 0;` `    ``int` `count2 = 0;` `    ``int` `m = n;` `    ``int` `len = 0;` ` `  `    ` `    ``whereas` `(m) {` `        ``len++;` `        ``m = m >> 1;` `    ``}` ` `  `    ``for` `(``int` `i = 0; i < len; i++) {` ` `  `        ` `        ``if` `(i % 2 == 0) {` `            ``if` `(n & 1 << i) {` `                ``count1++;` `            ``}` `        ``}` ` `  `        ` `        ``else` `{` `            ``if` `(n & 1 << i) {` `                ``count2++;` `            ``}` `        ``}` `    ``}` ` `  `    ` `    ``int` `diff = count1 - count2;` `    ``return` `diff;` `}` ` `  `int` `most important()` `{` ` `  `    ``int` `n = 17;` ` `  `    ` `    ``cout << diffEvenOddBit(n) << ``" "``;` `    ``return` `0;` `}`

Time Complexity: O(logn)
Auxiliary Area: O(1)Associated Articles:

Associated Articles: