Given a positive integer** N**, the task is to find out the sum of all consecutive bit differences from 0 to N. **Note: **If the bit length is different for two numbers like(3, 4) then append 0 at the beginning (011, 100). **Examples:**

Input:N = 3Output:4Explanation:

Bit differences of (0, 1) + (1, 2) + (2, 3) = 1 + 2 + 1 = 4.Input:N = 7Output:11

**Naive Approach:**

The simplest approach is to compare the two consecutive values within the range bitwise and find out by how many bits both these numbers differ. Add this bit difference to the sum. The final sum thus obtained is the required solution. **Time Complexity:** O(N)**Approach:**

Following observations are to be made to optimize the above solution:

- The consecutive bit differences of numbers follow a pattern i.e. every value X which is equal to (2
^{i}) has a bit difference of (i + 1) with its previous number and the (2^{i}– 1) numbers above X and (2^{i}– 1) numbers below X follow the same pattern. - For X = 4 (2
^{2}), i = 2 has a bit difference is (2 + 1) and the numbers (1, 2, 3) and (5, 6, 7) follow the same bit difference pattern.

For X = 4, the pattern is as follows: NUM BIT Diff 1 1(0, 1) 2 2(1, 2) 3 1(2, 3)4 3(3, 4)5 1(4, 5) 6 2(5, 6) 7 1(6, 7)

Follow the steps below to solve the problem:

- For every
**N**, find the nearest number less than or equal to N, which is a power of 2. Say that number is**M**. - For all the numbers less than M, the below recursive approach can be used to find out the sum of the consecutive bit differences.

Count(i) = (i + 1) + 2 * Count(i – 1)

where i is the exponent of the nearest power of 2.

- Initialize an array of size 65(0 – based indexing) to store the values obtained while using the recursive function Count(), so that in future, if the same values of Count() are needed, they can be directly obtained without recursively calling the Count() function to save time.
- Repeat the same process for the remaining numbers which are greater than M by using the below formula.

Sum = Sum + (i+1) + Count(i-1);

**For example:**

For N = 10, calculate the sum for the nearest power of 2 that is M = 8, using **Count(3)** and then repeat the process for remaining numbers greater than 8.

Below is the implementation of the above approach:

## CPP

`// CPP program for the above problem` `#include <bits/stdc++.h>` `using` `namespace` `std;` `long` `long` `a[65] = { 0 };` `// Recursive function to count` `// the sum of bit differences` `// of numbers from 1 to` `// pow(2, (i+1)) - 1` `long` `long` `Count(` `int` `i)` `{` ` ` `// base cases` ` ` `if` `(i == 0)` ` ` `return` `1;` ` ` `else` `if` `(i < 0)` ` ` `return` `0;` ` ` `// Recursion call if the sum` ` ` `// of bit difference of numbers` ` ` `// around i are not calculated` ` ` `if` `(a[i] == 0) {` ` ` `a[i] = (i + 1) + 2 * Count(i - 1);` ` ` `return` `a[i];` ` ` `}` ` ` `// return the sum of bit` ` ` `// differences if already` ` ` `// calculated` ` ` `else` ` ` `return` `a[i];` `}` `// Function to calculate the` `// sum of bit differences up to N` `long` `long` `solve(` `long` `long` `n)` `{` ` ` `long` `long` `i, sum = 0;` ` ` `while` `(n > 0) {` ` ` `// nearest smaller power` ` ` `// of 2` ` ` `i = log2(n);` ` ` `// remaining numbers` ` ` `n = n - ` `pow` `(2, i);` ` ` `// calculate the count` ` ` `// of bit diff` ` ` `sum = sum + (i + 1) + Count(i - 1);` ` ` `}` ` ` `return` `sum;` `}` `// Driver code` `int` `main()` `{` ` ` `long` `long` `n = 7;` ` ` `cout << solve(n) << endl;` ` ` `return` `0;` `}` |

*chevron_right*

*filter_none*

## Java

`// Java program for the above problem` `import` `java.util.*;` `class` `GFG{` ` ` `static` `int` `a[] = ` `new` `int` `[` `65` `]; ` ` ` `// Recursive function to count` `// the sum of bit differences` `// of numbers from 1 to` `// pow(2, (i+1)) - 1` `static` `int` `Count(` `int` `i)` `{` ` ` ` ` `// base cases` ` ` `if` `(i == ` `0` `)` ` ` `return` `1` `;` ` ` ` ` `else` `if` `(i < ` `0` `)` ` ` `return` `0` `;` ` ` ` ` `// Recursion call if the sum` ` ` `// of bit difference of numbers` ` ` `// around i are not calculated` ` ` `if` `(a[i] == ` `0` `) ` ` ` `{` ` ` `a[i] = (i + ` `1` `) + ` `2` `* Count(i - ` `1` `);` ` ` `return` `a[i];` ` ` `}` ` ` ` ` `// return the sum of bit` ` ` `// differences if already` ` ` `// calculated` ` ` `else` ` ` `return` `a[i];` `}` ` ` `// Function to calculate the` `// sum of bit differences up to N` `static` `int` `solve(` `int` `n)` `{` ` ` `int` `i, sum = ` `0` `;` ` ` ` ` `while` `(n > ` `0` `) ` ` ` `{` ` ` ` ` `// nearest smaller power` ` ` `// of 2` ` ` `i = (` `int` `)(Math.log(n) / Math.log(` `2` `)); ` ` ` ` ` `// remaining numbers` ` ` `n = n - (` `int` `)Math.pow(` `2` `, i);` ` ` ` ` `// calculate the count` ` ` `// of bit diff` ` ` `sum = sum + (i + ` `1` `) + Count(i - ` `1` `);` ` ` `}` ` ` `return` `sum;` `}` ` ` `// Driver code` `public` `static` `void` `main(String[] args)` `{` ` ` `int` `n = ` `7` `;` ` ` `System.out.println(solve(n)); ` `}` `}` `// This code is contributed by rock_cool` |

*chevron_right*

*filter_none*

**Output:**

11

**Time Complexity:** O(log(N)) **Auxiliary Space: **O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Maximize sum of consecutive differences in a circular array
- Largest increasing subsequence of consecutive integers
- Minimum increments to convert to an array of consecutive integers
- Construct a sequence from given frequencies of N consecutive integers with unit adjacent difference
- Maximize the sum of differences of consecutive elements after removing exactly K elements
- Minimize the sum of differences of consecutive elements after removing exactly K elements
- Find subarray with given sum | Set 1 (Nonnegative Numbers)
- Generate permutation of 1 to N such that absolute difference of consecutive numbers give K distinct integers
- Minimum product of k integers in an array of positive Integers
- Sum of bit differences for numbers from 0 to N | Set 2
- Sum of bit differences for numbers from 0 to N
- Sum of bit differences among all pairs
- Sum of subset differences
- Minimum sum of differences with an element in an array
- What are the differences between bitwise and logical AND operators in C/C++?
- Sum of absolute differences of all pairs in a given array
- Sum of all differences between Maximum and Minimum of increasing Subarrays
- Array element with minimum sum of absolute differences
- Minimum and Maximum sum of absolute differences of pairs
- Array formed using sum of absolute differences of that element with all other elements

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.