Given a positive integer N, the task is to count the total number of set bits in binary representation of all numbers from 1 to N.
Examples:
Input: N = 3
Output: 4
Explanation: Numbers from 1 to 3: {1, 2, 3}
Binary Representation of 1: 01 -> Set bits = 1
Binary Representation of 2: 10 -> Set bits = 1
Binary Representation of 3: 11 -> Set bits = 2
Total set bits from 1 till 3 = 1 + 1 + 2 = 4
Input: N = 6
Output: 9
Input: N = 7
Output: 12
Source: Amazon Interview Question
Count total set bits by converting each number into its Binary Representation:
The idea is to convert each number from 1 till N into binary, and count the set bits in each number separately.
Follow the steps below to understand how:
- Traverse a loop from 1 to N
- For each integer in 1 to N:
- Convert the number to its binary representation
- Add the count of 1s in the binary representation to the answer.
- Return the total set bits count.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
unsigned int countSetBitsUtil(unsigned int x);
unsigned int countSetBits(unsigned int n)
{
int bitCount = 0;
for ( int i = 1; i <= n; i++)
bitCount += countSetBitsUtil(i);
return bitCount;
}
unsigned int countSetBitsUtil(unsigned int x)
{
if (x <= 0)
return 0;
return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(x / 2);
}
int main()
{
int n = 4;
cout << "Total set bit count is " << countSetBits(n);
return 0;
}
|
C
#include <stdio.h>
unsigned int countSetBitsUtil(unsigned int x);
unsigned int countSetBits(unsigned int n)
{
int bitCount = 0;
for ( int i = 1; i <= n; i++)
bitCount += countSetBitsUtil(i);
return bitCount;
}
unsigned int countSetBitsUtil(unsigned int x)
{
if (x <= 0)
return 0;
return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(x / 2);
}
int main()
{
int n = 4;
printf ( "Total set bit count is %d" , countSetBits(n));
return 0;
}
|
Java
class GFG {
static int countSetBits( int n)
{
int bitCount = 0 ;
for ( int i = 1 ; i <= n; i++)
bitCount += countSetBitsUtil(i);
return bitCount;
}
static int countSetBitsUtil( int x)
{
if (x <= 0 )
return 0 ;
return (x % 2 == 0 ? 0 : 1 )
+ countSetBitsUtil(x / 2 );
}
public static void main(String[] args)
{
int n = 4 ;
System.out.print( "Total set bit count is " );
System.out.print(countSetBits(n));
}
}
|
Python3
def countSetBits(n):
bitCount = 0
for i in range ( 1 , n + 1 ):
bitCount + = countSetBitsUtil(i)
return bitCount
def countSetBitsUtil(x):
if (x < = 0 ):
return 0
return ( 0 if int (x % 2 ) = = 0 else 1 ) + countSetBitsUtil( int (x / 2 ))
if __name__ = = '__main__' :
n = 4
print ( "Total set bit count is" , countSetBits(n))
|
C#
using System;
class GFG {
static int countSetBits( int n)
{
int bitCount = 0;
for ( int i = 1; i <= n; i++)
bitCount += countSetBitsUtil(i);
return bitCount;
}
static int countSetBitsUtil( int x)
{
if (x <= 0)
return 0;
return (x % 2 == 0 ? 0 : 1)
+ countSetBitsUtil(x / 2);
}
public static void Main()
{
int n = 4;
Console.Write( "Total set bit count is " );
Console.Write(countSetBits(n));
}
}
|
Javascript
function countSetBits(n)
{
let bitCount = 0;
for (let i = 1; i <= n; i++)
{
bitCount += countSetBitsUtil(i);
}
return bitCount;
}
function countSetBitsUtil(x)
{
if (x <= 0)
{
return 0;
}
return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(Math.floor(x/2));
}
let n = 4;
console.log( "Total set bit count is " );
console.log(countSetBits(n));
|
PHP
<?php
function countSetBits( $n )
{
$bitCount = 0;
for ( $i = 1; $i <= $n ; $i ++)
$bitCount += countSetBitsUtil( $i );
return $bitCount ;
}
function countSetBitsUtil( $x )
{
if ( $x <= 0)
return 0;
return ( $x % 2 == 0 ? 0 : 1) +
countSetBitsUtil( $x / 2);
}
$n = 4;
echo "Total set bit count is " .
countSetBits( $n );
?>
|
Output
Total set bit count is 5
Time Complexity: O(N*log(N)), where N is the given integer and log(N) time is used for the binary conversion of the number.
Auxiliary Space: O(1).
Method 2 (Simple and efficient than Method 1)
If we observe bits from rightmost side at distance i than bits get inverted after 2^i position in vertical sequence.
for example n = 5;
0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
Observe the right most bit (i = 0) the bits get flipped after (2^0 = 1)
Observe the 3rd rightmost bit (i = 2) the bits get flipped after (2^2 = 4)
So, We can count bits in vertical fashion such that at i’th right most position bits will be get flipped after 2^i iteration;
C++
#include <bits/stdc++.h>
using namespace std;
int countSetBits( int n)
{
int i = 0;
int ans = 0;
while ((1 << i) <= n) {
bool k = 0;
int change = 1 << i;
for ( int j = 0; j <= n; j++) {
ans += k;
if (change == 1) {
k = !k;
change = 1 << i;
}
else {
change--;
}
}
i++;
}
return ans;
}
int main()
{
int n = 17;
cout << countSetBits(n) << endl;
return 0;
}
|
Java
public class GFG {
static int countSetBits( int n)
{
int i = 0 ;
int ans = 0 ;
while (( 1 << i) <= n) {
boolean k = false ;
int change = 1 << i;
for ( int j = 0 ; j <= n; j++) {
if (k == true )
ans += 1 ;
else
ans += 0 ;
if (change == 1 ) {
k = !k;
change = 1 << i;
}
else {
change--;
}
}
i++;
}
return ans;
}
public static void main(String[] args)
{
int n = 17 ;
System.out.println(countSetBits(n));
}
}
|
Python3
def countSetBits(n):
i = 0
ans = 0
while (( 1 << i) < = n):
k = 0
change = 1 << i
for j in range ( 0 , n + 1 ):
ans + = k
if change = = 1 :
k = not k
change = 1 << i
else :
change - = 1
i + = 1
return ans
if __name__ = = "__main__" :
n = 17
print (countSetBits(n))
|
C#
using System;
class GFG {
static int countSetBits( int n)
{
int i = 0;
int ans = 0;
while ((1 << i) <= n) {
bool k = false ;
int change = 1 << i;
for ( int j = 0; j <= n; j++) {
if (k == true )
ans += 1;
else
ans += 0;
if (change == 1) {
k = !k;
change = 1 << i;
}
else {
change--;
}
}
i++;
}
return ans;
}
static void Main()
{
int n = 17;
Console.Write(countSetBits(n));
}
}
|
Javascript
<script>
function countSetBits(n)
{
let i = 0;
let ans = 0;
while ((1 << i) <= n) {
let k = 0;
let change = 1 << i;
for (let j = 0; j <= n; j++) {
ans += k;
if (change == 1) {
k = !k;
change = 1 << i;
}
else {
change--;
}
}
i++;
}
return ans;
}
let n = 17;
document.write(countSetBits(n));
</script>
|
PHP
<?php
function countSetBits( $n )
{
$i = 0;
$ans = 0;
while ((1 << $i ) <= $n )
{
$k = 0;
$change = 1 << $i ;
for ( $j = 0; $j <= $n ; $j ++)
{
$ans += $k ;
if ( $change == 1)
{
$k = ! $k ;
$change = 1 << $i ;
}
else
{
$change --;
}
}
$i ++;
}
return $ans ;
}
$n = 17;
echo (countSetBits( $n ));
?>
|
Time Complexity: O(k*n)
where k = number of bits to represent number n
k <= 64
Method 3 (Tricky)
If the input number is of the form 2^b -1 e.g., 1, 3, 7, 15.. etc, the number of set bits is b * 2^(b-1). This is because for all the numbers 0 to (2^b)-1, if you complement and flip the list you end up with the same list (half the bits are on, half off).
If the number does not have all set bits, then some position m is the position of leftmost set bit. The number of set bits in that position is n – (1 << m) + 1. The remaining set bits are in two parts:
1) The bits in the (m-1) positions down to the point where the leftmost bit becomes 0, and
2) The 2^(m-1) numbers below that point, which is the closed form above.
An easy way to look at it is to consider the number 6:
0|0 0
0|0 1
0|1 0
0|1 1
-|--
1|0 0
1|0 1
1|1 0
The leftmost set bit is in position 2 (positions are considered starting from 0). If we mask that off what remains is 2 (the “1 0” in the right part of the last row.) So the number of bits in the 2nd position (the lower left box) is 3 (that is, 2 + 1). The set bits from 0-3 (the upper right box above) is 2*2^(2-1) = 4. The box in the lower right is the remaining bits we haven’t yet counted, and is the number of set bits for all the numbers up to 2 (the value of the last entry in the lower right box) which can be figured recursively.
C++
#include <bits/stdc++.h>
using namespace std;
unsigned int getLeftmostBit( int n)
{
int m = 0;
while (n > 1) {
n = n >> 1;
m++;
}
return m;
}
unsigned int getNextLeftmostBit( int n, int m)
{
unsigned int temp = 1 << m;
while (n < temp) {
temp = temp >> 1;
m--;
}
return m;
}
unsigned int _countSetBits(unsigned int n, int m);
unsigned int countSetBits(unsigned int n)
{
int m = getLeftmostBit(n);
return _countSetBits(n, m);
}
unsigned int _countSetBits(unsigned int n, int m)
{
if (n == 0)
return 0;
m = getNextLeftmostBit(n, m);
if (n == ((unsigned int )1 << (m + 1)) - 1)
return (unsigned int )(m + 1) * (1 << m);
n = n - (1 << m);
return (n + 1) + countSetBits(n) + m * (1 << (m - 1));
}
int main()
{
int n = 17;
cout << "Total set bit count is " << countSetBits(n);
return 0;
}
|
C
#include <stdio.h>
unsigned int getLeftmostBit( int n)
{
int m = 0;
while (n > 1) {
n = n >> 1;
m++;
}
return m;
}
unsigned int getNextLeftmostBit( int n, int m)
{
unsigned int temp = 1 << m;
while (n < temp) {
temp = temp >> 1;
m--;
}
return m;
}
unsigned int _countSetBits(unsigned int n, int m);
unsigned int countSetBits(unsigned int n)
{
int m = getLeftmostBit(n);
return _countSetBits(n, m);
}
unsigned int _countSetBits(unsigned int n, int m)
{
if (n == 0)
return 0;
m = getNextLeftmostBit(n, m);
if (n == ((unsigned int )1 << (m + 1)) - 1)
return (unsigned int )(m + 1) * (1 << m);
n = n - (1 << m);
return (n + 1) + countSetBits(n) + m * (1 << (m - 1));
}
int main()
{
int n = 17;
printf ( "Total set bit count is %d" , countSetBits(n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int getLeftmostBit( int n)
{
int m = 0 ;
while (n > 1 ) {
n = n >> 1 ;
m++;
}
return m;
}
static int getNextLeftmostBit( int n, int m)
{
int temp = 1 << m;
while (n < temp) {
temp = temp >> 1 ;
m--;
}
return m;
}
static int countSetBits( int n)
{
int m = getLeftmostBit(n);
return countSetBits(n, m);
}
static int countSetBits( int n, int m)
{
if (n == 0 )
return 0 ;
m = getNextLeftmostBit(n, m);
if (n == (( int ) 1 << (m + 1 )) - 1 )
return ( int )(m + 1 ) * ( 1 << m);
n = n - ( 1 << m);
return (n + 1 ) + countSetBits(n)
+ m * ( 1 << (m - 1 ));
}
public static void main(String[] args)
{
int n = 17 ;
System.out.println( "Total set bit count is "
+ countSetBits(n));
}
}
|
Python3
def getLeftmostBit(n):
m = 0
while (n > 1 ):
n = n >> 1
m + = 1
return m
def getNextLeftmostBit(n, m):
temp = 1 << m
while (n < temp):
temp = temp >> 1
m - = 1
return m
def countSetBits(n):
m = getLeftmostBit(n)
return _countSetBits(n, m)
def _countSetBits(n, m):
if (n = = 0 ):
return 0
m = getNextLeftmostBit(n, m)
if (n = = ( 1 << (m + 1 )) - 1 ):
return ((m + 1 ) * ( 1 << m))
n = n - ( 1 << m)
return (n + 1 ) + countSetBits(n) + m * ( 1 << (m - 1 ))
n = 17
print ( "Total set bit count is" , countSetBits(n))
|
C#
using System;
class GFG {
static int getLeftmostBit( int n)
{
int m = 0;
while (n > 1) {
n = n >> 1;
m++;
}
return m;
}
static int getNextLeftmostBit( int n, int m)
{
int temp = 1 << m;
while (n < temp) {
temp = temp >> 1;
m--;
}
return m;
}
static int countSetBits( int n)
{
int m = getLeftmostBit(n);
return countSetBits(n, m);
}
static int countSetBits( int n, int m)
{
if (n == 0)
return 0;
m = getNextLeftmostBit(n, m);
if (n == (( int )1 << (m + 1)) - 1)
return ( int )(m + 1) * (1 << m);
n = n - (1 << m);
return (n + 1) + countSetBits(n)
+ m * (1 << (m - 1));
}
static public void Main()
{
int n = 17;
Console.Write( "Total set bit count is "
+ countSetBits(n));
}
}
|
Javascript
<script>
function getLeftmostBit(n)
{
let m = 0;
while (n > 1)
{
n = n >> 1;
m++;
}
return m;
}
function getNextLeftmostBit(n,m)
{
let temp = 1 << m;
while (n < temp)
{
temp = temp >> 1;
m--;
}
return m;
}
function countSetBits(n)
{
let m = getLeftmostBit(n);
return _countSetBits(n, m);
}
function _countSetBits(n,m)
{
if (n == 0)
return 0;
m = getNextLeftmostBit(n, m);
if (n == (1 << (m + 1)) - 1)
return (m + 1) * (1 << m);
n = n - (1 << m);
return (n + 1) + countSetBits(n) + m * (1 << (m - 1));
}
let n = 17;
document.write( "Total set bit count is " + countSetBits(n));
</script>
|
Output
Total set bit count is 35
Time Complexity: O(Logn). From the first look at the implementation, time complexity looks more. But if we take a closer look, statements inside while loop of getNextLeftmostBit() are executed for all 0 bits in n. And the number of times recursion is executed is less than or equal to set bits in n. In other words, if the control goes inside while loop of getNextLeftmostBit(), then it skips those many bits in recursion.
Thanks to agatsu and IC for suggesting this solution.
Here is another solution suggested by Piyush Kapoor.
A simple solution , using the fact that for the ith least significant bit, answer will be
(N/2^i)*2^(i-1)+ X
where
X = N%(2^i)-(2^(i-1)-1)
if
N%(2^i)>(2^(i-1)-1)
C++
int getSetBitsFromOneToN( int N)
{
int two = 2, ans = 0;
int n = N;
while (n) {
ans += (N / two) * (two >> 1);
if ((N & (two - 1)) > (two >> 1) - 1)
ans += (N & (two - 1)) - (two >> 1) + 1;
two <<= 1;
n >>= 1;
}
return ans;
}
|
Java
static int getSetBitsFromOneToN( int N)
{
int two = 2 , ans = 0 ;
int n = N;
while (n != 0 ) {
ans += (N / two) * (two >> 1 );
if ((N & (two - 1 )) > (two >> 1 ) - 1 )
ans += (N & (two - 1 )) - (two >> 1 ) + 1 ;
two <<= 1 ;
n >>= 1 ;
}
return ans;
}
|
Python3
def getSetBitsFromOneToN(N):
two = 2
ans = 0
n = N
while (n ! = 0 )
{
ans + = int (N / two) * (two >> 1 )
if ((N & (two - 1 )) > (two >> 1 ) - 1 ):
ans + = (N & (two - 1 )) - (two >> 1 ) + 1
two << = 1
n >> = 1
}
return ans
|
C#
static int getSetBitsFromOneToN( int N)
{
int two = 2, ans = 0;
int n = N;
while (n != 0) {
ans += (N / two) * (two >> 1);
if ((N & (two - 1)) > (two >> 1) - 1)
ans += (N & (two - 1)) - (two >> 1) + 1;
two <<= 1;
n >>= 1;
}
return ans;
}
|
Javascript
<script>
function getSetBitsFromOneToN(N)
{
var two = 2
var ans = 0
var n = N
while (n != 0)
{
ans += Math.floor(N / two) * (two >> 1)
if ((N & (two - 1)) > (two >> 1) - 1)
ans += (N&(two - 1)) - (two >> 1) + 1
two <<= 1;
n >>= 1;
}
return ans
}
</script>
|
Method 4 (Recursive)
Approach:
For each number ‘n’, there will be a number a, where a<=n and a is perfect power of two, like 1,2,4,8…..
Let n = 11, now we can see that
Numbers till n, are:
0 -> 0000000
1 -> 0000001
2 -> 0000010
3 -> 0000011
4 -> 0000100
5 -> 0000101
6 -> 0000110
7 -> 0000111
8 -> 0001000
9 -> 0001001
10 -> 0001010
11 -> 0001011
Now we can see that, from 0 to pow(2,1)-1 = 1, we can pair elements top-most with bottom-most,
and count of set bit in a pair is 1
Similarly for pow(2,2)-1 = 4, pairs are:
00 and 11
01 and 10
here count of set bit in a pair is 2, so in both pairs is 4
Similarly we can see for 7, 15, ans soon.....
so we can generalise that,
count(x) = (x*pow(2,(x-1))),
here x is position of set bit of the largest power of 2 till n
for n = 8, x = 3
for n = 4, x = 2
for n = 5, x = 2
so now for n = 11,
we have added set bits count from 0 to 7 using count(x) = (x*pow(2,(x-1)))
for rest numbers 8 to 11, all will have a set bit at 3rd index, so we can add
count of rest numbers to our ans,
which can be calculated using 11 - 8 + 1 = (n-pow(2,x) + 1)
Now if notice that, after removing front bits from rest numbers, we get again number from 0 to some m
so we can recursively call our same function for next set of numbers,
by calling countSetBits(n - pow(2,x))
8 -> 1000 -> 000 -> 0
9 -> 1001 -> 001 -> 1
10 -> 1010 -> 010 -> 2
11 -> 1011 -> 011 -> 3
Code:
C++
#include <bits/stdc++.h>
using namespace std;
int findLargestPower( int n)
{
int x = 0;
while ((1 << x) <= n)
x++;
return x - 1;
}
int countSetBits( int n)
{
if (n <= 1)
return n;
int x = findLargestPower(n);
return (x * pow (2, (x - 1))) + (n - pow (2, x) + 1)
+ countSetBits(n - pow (2, x));
}
int main()
{
int N = 17;
cout << countSetBits(N) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int findLargestPower( int n)
{
int x = 0 ;
while (( 1 << x) <= n)
x++;
return x - 1 ;
}
static int countSetBits( int n)
{
if (n <= 1 )
return n;
int x = findLargestPower(n);
return (x * ( int )Math.pow( 2 , (x - 1 )))
+ (n - ( int )Math.pow( 2 , x) + 1 )
+ countSetBits(n - ( int )Math.pow( 2 , x));
}
public static void main(String[] args)
{
int N = 17 ;
System.out.print(countSetBits(N));
}
}
|
Python3
def findLargestPower(n):
x = 0
while (( 1 << x) < = n):
x + = 1
return x - 1
def countSetBits(n):
if (n < = 1 ):
return n
x = findLargestPower(n)
return (x * pow ( 2 , (x - 1 ))) + (n - pow ( 2 , x) + 1 ) + countSetBits(n - pow ( 2 , x))
N = 17
print (countSetBits(N))
|
C#
using System;
class GFG {
static int findLargestPower( int n)
{
int x = 0;
while ((1 << x) <= n)
x++;
return x - 1;
}
static int countSetBits( int n)
{
if (n <= 1)
return n;
int x = findLargestPower(n);
return (x * ( int )Math.Pow(2, (x - 1)))
+ (n - ( int )Math.Pow(2, x) + 1)
+ countSetBits(n - ( int )Math.Pow(2, x));
}
public static void Main( string [] args)
{
int N = 17;
Console.Write(countSetBits(N));
}
}
|
Javascript
<script>
function findLargestPower(n)
{
var x = 0;
while ((1 << x) <= n)
x++;
return x - 1;
}
function countSetBits(n)
{
if (n <= 1)
return n;
var x = findLargestPower(n);
return (x * Math.pow(2, (x - 1))) + (n - Math.pow(2, x) + 1) + countSetBits(n - Math.pow(2, x));
}
var N = 17;
document.write(countSetBits(N));
</script>
|
Time Complexity: O(LogN)
Method 5(Iterative)
Example:
0 -> 0000000 8 -> 001000 16 -> 010000 24 -> 011000
1 -> 0000001 9 -> 001001 17 -> 010001 25 -> 011001
2 -> 0000010 10 -> 001010 18 -> 010010 26 -> 011010
3 -> 0000011 11 -> 001011 19 -> 010010 27 -> 011011
4 -> 0000100 12 -> 001100 20 -> 010100 28 -> 011100
5 -> 0000101 13 -> 001101 21 -> 010101 29 -> 011101
6 -> 0000110 14 -> 001110 22 -> 010110 30 -> 011110
7 -> 0000111 15 -> 001111 23 -> 010111 31 -> 011111
Input: N = 4
Output: 5
Input: N = 17
Output: 35
Approach : Pattern recognition
Let ‘N’ be any arbitrary number and consider indexing from right to left(rightmost being 1); then nearestPow = pow(2,i).
Now, when you write all numbers from 1 to N, you will observe the pattern mentioned below:
For every index i, there are exactly nearestPow/2 continuous elements that are unset followed by nearestPow/2 elements that are set.
Throughout the solution, i am going to use this concept.
You can clearly observe above concept in the above table.
The general formula that i came up with:
a. addRemaining = mod – (nearestPos/2) + 1 if mod >= nearestPow/2;
b. totalSetBitCount = totalRep*(nearestPow/2) + addRemaining
where totalRep -> total number of times the pattern repeats at index i
addRemaining -> total number of set bits left to be added after the pattern is exhausted
Eg: let N = 17
leftMostSetIndex = 5 (Left most set bit index, considering 1 based indexing)
i = 1 => nearestPos = pow(2,1) = 2; totalRep = (17+1)/2 = 9 (add 1 only for i=1)
mod = 17%2 = 1
addRemaining = 0 (only for base case)
totalSetBitCount = totalRep*(nearestPos/2) + addRemaining = 9*(2/2) + 0 = 9*1 + 0 = 9
i = 2 => nearestPos = pow(2, 2)=4; totalRep = 17/4 = 4
mod = 17%4 = 1
mod(1) < (4/2) => 1 < 2 => addRemaining = 0
totalSetBitCount = 9 + 4*(2) + 0 = 9 + 8 = 17
i = 3 => nearestPow = pow(2,3) = 8; totalRep = 17/8 = 2
mod = 17%8 = 1
mod < 4 => addRemaining = 0
totalSetBitCount = 17 + 2*(4) + 0 = 17 + 8 + 0 = 25
i = 4 => nearestPow = pow(2, 4) = 16; totalRep = 17/16 = 1
mod = 17%16 = 1
mod < 8 => addRemaining = 0
totalSetBitCount = 25 + 1*(8) + 0 = 25 + 8 + 0 = 33
We cannot simply operate on the next power(32) as 32>17. Also, as the first half bits will be 0s only, we need to find the distance of the given number(17) from the last power to directly get the number of 1s to be added
i = 5 => nearestPow = (2, 5) = 32 (base case 2)
lastPow = pow(2, 4) = 16
mod = 17%16 = 1
totalSetBit = 33 + (mod+1) = 33 + 1 + 1 = 35
Therefore, total num of set bits from 1 to 17 is 35
Try iterating with N = 30, for better understanding of the solution.
Solution
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int GetLeftMostSetBit( int n)
{
int pos = 0;
while (n > 0) {
pos++;
n >>= 1;
}
return pos;
}
int TotalSetBitsFrom1ToN( int n)
{
int leftMostSetBitInd = GetLeftMostSetBit(n);
int totalRep, mod;
int nearestPow;
int totalSetBitCount = 0;
int addRemaining = 0;
int curr
= 0;
for ( int i = 1; i <= leftMostSetBitInd; ++i) {
nearestPow = pow (2, i);
if (nearestPow > n) {
int lastPow = pow (2, i - 1);
mod = n % lastPow;
totalSetBitCount += mod + 1;
}
else {
if (i == 1 && n % 2 == 1) {
totalRep = (n + 1) / nearestPow;
mod = nearestPow % 2;
addRemaining = 0;
}
else {
totalRep = n / nearestPow;
mod = n % nearestPow;
if (mod >= (nearestPow / 2)) {
addRemaining
= mod - (nearestPow / 2) + 1;
}
else {
addRemaining = 0;
}
}
curr = totalRep * (nearestPow / 2)
+ addRemaining;
totalSetBitCount += curr;
}
}
return totalSetBitCount;
}
int main()
{
std::cout << TotalSetBitsFrom1ToN(4) << endl;
std::cout << TotalSetBitsFrom1ToN(17) << endl;
std::cout << TotalSetBitsFrom1ToN(30) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int GetLeftMostSetBit( int n)
{
int pos = 0 ;
while (n > 0 ) {
pos++;
n >>= 1 ;
}
return pos;
}
static int TotalSetBitsFrom1ToN( int n)
{
int leftMostSetBitInd = GetLeftMostSetBit(n);
int totalRep, mod;
int nearestPow;
int totalSetBitCount = 0 ;
int addRemaining = 0 ;
int curr = 0 ;
for ( int i = 1 ; i <= leftMostSetBitInd; ++i) {
nearestPow = ( int )Math.pow( 2 , i);
if (nearestPow > n) {
int lastPow = ( int )Math.pow( 2 , i - 1 );
mod = n % lastPow;
totalSetBitCount += mod + 1 ;
}
else {
if (i == 1 && n % 2 == 1 ) {
totalRep = (n + 1 ) / nearestPow;
mod = nearestPow % 2 ;
addRemaining = 0 ;
}
else {
totalRep = n / nearestPow;
mod = n % nearestPow;
if (mod >= (nearestPow / 2 )) {
addRemaining
= mod - (nearestPow / 2 ) + 1 ;
}
else {
addRemaining = 0 ;
}
}
curr = totalRep * (nearestPow / 2 )
+ addRemaining;
totalSetBitCount += curr;
}
}
return totalSetBitCount;
}
public static void main(String[] args)
{
System.out.println(TotalSetBitsFrom1ToN( 4 ));
System.out.println(TotalSetBitsFrom1ToN( 17 ));
System.out.println(TotalSetBitsFrom1ToN( 30 ));
}
}
|
Python3
def get_left_most_set_bit(n):
left_most_set_bit_indx = 0
while n > 0 :
left_most_set_bit_indx + = 1
n >> = 1
return left_most_set_bit_indx
def total_set_bits_from_1_to_n(n):
left_most_set_bit_indx = get_left_most_set_bit(n)
total_rep = 0
mod = 0
nearest_pow = 0
total_set_bit_count = 0
add_remaining = 0
curr = 0
for i in range ( 1 , left_most_set_bit_indx + 1 ):
nearest_pow = pow ( 2 , i)
if nearest_pow > n:
last_pow = pow ( 2 , i - 1 )
mod = n % last_pow
total_set_bit_count + = mod + 1
else :
if i = = 1 and n % 2 = = 1 :
total_rep = (n + 1 ) / nearest_pow
mod = nearest_pow % 2
add_remaining = 0
else :
total_rep = int (n / nearest_pow)
mod = n % nearest_pow
add_remaining = int (
mod - (nearest_pow / 2 ) + 1 ) if mod > = nearest_pow / 2 else 0
curr = int (total_rep * (nearest_pow / 2 ) + add_remaining)
total_set_bit_count + = curr
return total_set_bit_count
if __name__ = = "__main__" :
print (total_set_bits_from_1_to_n( 4 ))
print (total_set_bits_from_1_to_n( 17 ))
print (total_set_bits_from_1_to_n( 30 ))
|
C#
using System;
public class GFG {
static int GetLeftMostSetBit( int n)
{
int pos = 0;
while (n > 0) {
pos++;
n >>= 1;
}
return pos;
}
static int TotalSetBitsFrom1ToN( int n)
{
int leftMostSetBitInd = GetLeftMostSetBit(n);
int totalRep, mod;
int nearestPow;
int totalSetBitCount = 0;
int addRemaining = 0;
int curr = 0;
for ( int i = 1; i <= leftMostSetBitInd; ++i) {
nearestPow = ( int )Math.Pow(2, i);
if (nearestPow > n) {
int lastPow = ( int )Math.Pow(2, i - 1);
mod = n % lastPow;
totalSetBitCount += mod + 1;
}
else {
if (i == 1 && n % 2 == 1) {
totalRep = (n + 1) / nearestPow;
mod = nearestPow % 2;
addRemaining = 0;
}
else {
totalRep = n / nearestPow;
mod = n % nearestPow;
if (mod >= (nearestPow / 2)) {
addRemaining
= mod - (nearestPow / 2) + 1;
}
else {
addRemaining = 0;
}
}
curr = totalRep * (nearestPow / 2)
+ addRemaining;
totalSetBitCount += curr;
}
}
return totalSetBitCount;
}
public static void Main(String[] args)
{
Console.WriteLine(TotalSetBitsFrom1ToN(4));
Console.WriteLine(TotalSetBitsFrom1ToN(17));
Console.WriteLine(TotalSetBitsFrom1ToN(30));
}
}
|
Javascript
<script>
function GetLeftMostSetBit(n) {
var pos = 0;
while (n > 0) {
pos++;
n >>= 1;
}
return pos;
}
function TotalSetBitsFrom1ToN(n) {
var leftMostSetBitInd = GetLeftMostSetBit(n);
var totalRep, mod;
var nearestPow;
var totalSetBitCount = 0;
var addRemaining = 0;
var curr = 0;
for ( var i = 1; i <= leftMostSetBitInd; ++i) {
nearestPow = parseInt( Math.pow(2, i));
if (nearestPow > n) {
var lastPow = parseInt( Math.pow(2, i - 1));
mod = n % lastPow;
totalSetBitCount += mod + 1;
} else {
if (i == 1 && n % 2 == 1) {
totalRep = parseInt((n + 1) / nearestPow);
mod = nearestPow % 2;
addRemaining = 0;
} else {
totalRep =parseInt( n / nearestPow);
mod = n % nearestPow;
if (mod >= parseInt(nearestPow / 2)) {
addRemaining = mod - parseInt(nearestPow / 2) + 1;
} else {
addRemaining = 0;
}
}
curr = totalRep * (parseInt(nearestPow / 2)) + addRemaining;
totalSetBitCount += curr;
}
}
return totalSetBitCount;
}
document.write(TotalSetBitsFrom1ToN(4));
document.write( "<br/>" +TotalSetBitsFrom1ToN(17));
document.write( "<br/>" +TotalSetBitsFrom1ToN(30));
</script>
|
Time Complexity: O(log(n))
Method 6 ( Using Inbuilt Functions )
__builtin_popcount(): Counts a number of set bits in a number.
C++
#include <bits/stdc++.h>
#include <iostream>
int TotalSetBitsFrom1ToN( int n)
{
int totalSetBitCount = 0;
for ( int number = 1 ; number <= n ;number++)
{
totalSetBitCount+=__builtin_popcount(number);
}
return totalSetBitCount;
}
int main()
{
std::cout << TotalSetBitsFrom1ToN(4) << std::endl;
std::cout << TotalSetBitsFrom1ToN(17) << std::endl;
std::cout << TotalSetBitsFrom1ToN(30) << std::endl;
return 0;
}
|
Java
public class GFG {
public static int totalSetBitsFrom1ToN( int n) {
int totalSetBitCount = 0 ;
for ( int number = 1 ; number <= n; number++) {
totalSetBitCount += Integer.bitCount(number);
}
return totalSetBitCount;
}
public static void main(String[] args) {
System.out.println(totalSetBitsFrom1ToN( 4 ));
System.out.println(totalSetBitsFrom1ToN( 17 ));
System.out.println(totalSetBitsFrom1ToN( 30 ));
}
}
|
Python3
def total_set_bits_from_1_to_n(n):
total_set_bit_count = 0
for number in range ( 1 , n + 1 ):
total_set_bit_count + = bin (number).count( '1' )
return total_set_bit_count
def main():
print ( "Total set bits from 1 to 4:" , total_set_bits_from_1_to_n( 4 ))
print ( "Total set bits from 1 to 17:" , total_set_bits_from_1_to_n( 17 ))
print ( "Total set bits from 1 to 30:" , total_set_bits_from_1_to_n( 30 ))
if __name__ = = "__main__" :
main()
|
C#
using System;
class GFG
{
static int TotalSetBitsFrom1ToN( int n)
{
int totalSetBitCount = 0;
for ( int number = 1; number <= n; number++)
{
totalSetBitCount += BitCount(number);
}
return totalSetBitCount;
}
static int BitCount( int number)
{
int count = 0;
while (number > 0)
{
count += number & 1;
number >>= 1;
}
return count;
}
static void Main( string [] args)
{
Console.WriteLine(TotalSetBitsFrom1ToN(4));
Console.WriteLine(TotalSetBitsFrom1ToN(17));
Console.WriteLine(TotalSetBitsFrom1ToN(30));
}
}
|
Javascript
function totalSetBitsFrom1ToN(n) {
let totalSetBitCount = 0;
for (let number = 1; number <= n; number++) {
totalSetBitCount += number.toString(2).split( '1' ).length - 1;
}
return totalSetBitCount;
}
console.log(totalSetBitsFrom1ToN(4));
console.log(totalSetBitsFrom1ToN(17));
console.log(totalSetBitsFrom1ToN(30));
|
Time Complexity: O(n*k) ,where n is total numbers and k is total number of bits in the number.
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...