Given a number N, the task is to calculate the total number of corresponding different bit in the binary representation for every consecutive number from 0 to N.
Input: N = 5
Binary Representation of numbers are:
0 -> 000,
1 -> 001,
2 -> 010,
3 -> 011,
4 -> 100,
5 -> 101
Between 1 and 0 -> 1 bit is different
Between 2 and 1 -> 2 bits are different
Between 3 and 2 -> 1 bit is different
Between 4 and 3 -> 3 bits are different
Between 5 and 4 -> 1 bit is different
Total = 1 + 2 + 1 + 3 + 1 = 8
Input: N = 11
For Naive and Efficient Approach please refer to the previous post of this article.
More Efficient Approach: To optimize the above methods, we can use Recursion. To solve the problem, the following observations need to be made
Number: 0 1 2 3 4 5 6 7 Difference: 1 2 1 3 1 2 1 4 Sum: 1 3 4 7 8 10 11 15
We can observe that for N = [1, 2, 3, 4, …..], the sum of different bits in consecutive elements forms the sequence [1, 3, 4, 7, 8, ……]. Hence, Nth term of this series will be our required answer, which can be calculated as:
a(n) = a(n / 2) + n; with base case as a(1) = 1
Below is the implementation for above Recursive approach:
Time Complexity: O(log2N)
Auxiliary Space: O(1)
- Sum of bit differences for numbers from 0 to N
- Sum of bit differences among all pairs
- Sum of consecutive bit differences of first N non-negative integers
- Inserting M into N such that m starts at bit j and ends at bit i | Set-2
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- Inserting m into n such that m starts at bit j and ends at bit i.
- Count of 1-bit and 2-bit characters in the given binary string
- Sequence with sum K and minimum sum of absolute differences between consecutive elements
- Sum of all the prime numbers with the maximum position of set bit ≤ D
- Maximize the sum of differences of consecutive elements after removing exactly K elements
- Array formed using sum of absolute differences of that element with all other elements
- Sum of all differences between Maximum and Minimum of increasing Subarrays
- Count of numbers having only 1 set bit in the range [0, n]
- Maximum set bit sum in array without considering adjacent elements
- Maximum set bit count from pairs of integers from 0 to N that yields a sum as N
- Turn off the rightmost set bit | Set 2
- What are the differences between bitwise and logical AND operators in C/C++?
- Minimum elements to be inserted in Array to make adjacent differences equal
- Check if two numbers are bit rotations of each other or not
- 1 to n bit numbers with no consecutive 1s in binary representation.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : himanshu77