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

Support Article

Save Article

Like Article

Support Article

Save Article

Like Article

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 <bits/stdc++.h>

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:

Like Article

Save Article

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: