Given a positive integer N, the task is to count the total number of unset bits in the binary representation of all the numbers from 1 to N. Note that leading zeroes will not be counted as unset bits.
Examples:
Input: N = 5
Output: 4
Integer |
Binary Representation |
Count of unset bits |
1 |
1 |
0 |
2 |
10 |
1 |
3 |
11 |
0 |
4 |
100 |
2 |
5 |
101 |
1 |
0 + 1 + 0 + 2 + 1 = 4
Input: N = 14
Output: 17
Approach:
- Iterate the loop from 1 to N.
- While number is greater than 0 divide it by 2 and check the remainder.
- If remainder is equal to 0 then increase the value of count by 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countUnsetBits( int n)
{
int cnt = 0;
for ( int i = 1; i <= n; i++) {
int temp = i;
while (temp) {
if (temp % 2 == 0)
cnt++;
temp = temp / 2;
}
}
return cnt;
}
int main()
{
int n = 5;
cout << countUnsetBits(n);
return 0;
}
|
Java
class GFG
{
static int countUnsetBits( int n)
{
int cnt = 0 ;
for ( int i = 1 ; i <= n; i++)
{
int temp = i;
while (temp > 0 )
{
if (temp % 2 == 0 )
{
cnt = cnt + 1 ;
}
temp = temp / 2 ;
}
}
return cnt;
}
public static void main(String[] args)
{
int n = 5 ;
System.out.println(countUnsetBits(n));
}
}
|
Python3
def countUnsetBits(n) :
cnt = 0 ;
for i in range ( 1 , n + 1 ) :
temp = i;
while (temp) :
if (temp % 2 = = 0 ) :
cnt + = 1 ;
temp = temp / / 2 ;
return cnt;
if __name__ = = "__main__" :
n = 5 ;
print (countUnsetBits(n));
|
C#
using System;
class GFG
{
static int countUnsetBits( int n)
{
int cnt = 0;
for ( int i = 1; i <= n; i++)
{
int temp = i;
while (temp > 0)
{
if (temp % 2 == 0)
cnt = cnt + 1;
temp = temp / 2;
}
}
return cnt;
}
public static void Main()
{
int n = 5;
Console.Write(countUnsetBits(n));
}
}
|
Javascript
<script>
function countUnsetBits(n)
{
var cnt = 0;
for ( var i = 1; i <= n; i++) {
var temp = i;
while (temp) {
if (temp % 2 == 0)
cnt++;
temp = parseInt(temp / 2);
}
}
return cnt;
}
var n = 5;
document.write( countUnsetBits(n));
</script>
|
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
12 Nov, 2021
Like Article
Save Article