Given an integer N, the duty is to search out absolutely the distinction of set bits at even and odd indices of quantity N. (0-based Indexing)
Enter: N = 15
Rationalization: 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
Rationalization: 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 thought:
Type a binary string of a given quantity N and begin iterating from the best 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 via every bit place, checking whether it is even or odd
- Finally, Depend 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:
Time Complexity: O(logn)
Auxiliary House: O(1)Associated Articles: