# In finding absolutely the distinction of set bits at even and ordinary indices of N

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

Examples:Â

Enter: N = 15
Output: 0
Rationalization: The binary illustration of 15 is 1111. So, it accommodates 1 at the 1st and third place and it accommodates 1 at the 0th and second place. Subsequently, the variation between even and ordinary bits is two â 2 which is 0.

Enter: N = 17
Output: 2
Rationalization: The binary illustration of 17 is 10001. So, it accommodates 1 at the 0th and 4th positions. Subsequently, the variation between even and ordinary bits is 2-0 which is two.

Means: This will also be solved with the next thought:

Shape a binary string of a given quantity N and get started iterating from the proper finish, keeping up the sum of numbers provide at even and ordinary indexes one after the other.Â

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

• Calculate the period of the binary illustration of the quantity.
• Iterating via every bit place, checking whether it is even or ordinary
• Ultimately, Depend the collection of set bits accordingly the use of bitwise operations.Â
• Go back absolutely the distinction between even and ordinary bits.

Beneath is the implementation of the code:

## C++

 `#come with ` `the use of` `namespace` `std;` `Â `Â  `int` `diffEvenOddBit(``int` `n)` `{` `Â `Â  `Â Â Â Â ``int` `count1 = 0;` `Â Â Â Â ``int` `count2 = 0;` `Â Â Â Â ``int` `m = n;` `Â Â Â Â ``int` `len = 0;` `Â `Â  `Â Â Â Â ` `Â Â Â Â ``whilst` `(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;` `Â Â Â Â ``go back` `diff;` `}` `Â `Â  `int` `primary()` `{` `Â `Â  `Â Â Â Â ``int` `n = 17;` `Â `Â  `Â Â Â Â ` `Â Â Â Â ``cout << diffEvenOddBit(n) << ``" "``;` `Â Â Â Â ``go back` `0;` `}`

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

Similar Articles: