给定一个正整数N ,任务是计算从1到N的所有数字的二进制表示形式中未设置位的总数。请注意,前导零不会被算作未设置的位。
例子:
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
方法:
- 将循环从1迭代到N。
- 当数字大于0时,将其除以2,然后检查余数。
- 如果余数等于0,则将count的值增加1 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count of unset
// bits in the binary representation of
// all the numbers from 1 to n
int countUnsetBits(int n)
{
// To store the count of unset bits
int cnt = 0;
// For every integer from the range [1, n]
for (int i = 1; i <= n; i++) {
// A copy of the current integer
int temp = i;
// Count of unset bits in
// the current integer
while (temp) {
// If current bit is unset
if (temp % 2 == 0)
cnt++;
temp = temp / 2;
}
}
return cnt;
}
// Driver code
int main()
{
int n = 5;
cout << countUnsetBits(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the count of unset
// bits in the binary representation of
// all the numbers from 1 to n
static int countUnsetBits(int n)
{
// To store the count of unset bits
int cnt = 0;
// For every integer from the range [1, n]
for (int i = 1; i <= n; i++)
{
// A copy of the current integer
int temp = i;
// Count of unset bits in
// the current integer
while (temp > 0)
{
// If current bit is unset
if (temp % 2 == 0)
{
cnt = cnt + 1;
}
temp = temp / 2;
}
}
return cnt;
}
// Driver code
public static void main(String[] args)
{
int n = 5;
System.out.println(countUnsetBits(n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
# Function to return the count of unset
# bits in the binary representation of
# all the numbers from 1 to n
def countUnsetBits(n) :
# To store the count of unset bits
cnt = 0;
# For every integer from the range [1, n]
for i in range(1, n + 1) :
# A copy of the current integer
temp = i;
# Count of unset bits in
# the current integer
while (temp) :
# If current bit is unset
if (temp % 2 == 0) :
cnt += 1;
temp = temp // 2;
return cnt;
# Driver code
if __name__ == "__main__" :
n = 5;
print(countUnsetBits(n));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the count of unset
// bits in the binary representation of
// all the numbers from 1 to n
static int countUnsetBits(int n)
{
// To store the count of unset bits
int cnt = 0;
// For every integer from the range [1, n]
for (int i = 1; i <= n; i++)
{
// A copy of the current integer
int temp = i;
// Count of unset bits in
// the current integer
while (temp > 0)
{
// If current bit is unset
if (temp % 2 == 0)
cnt = cnt + 1;
temp = temp / 2;
}
}
return cnt;
}
// Driver code
public static void Main()
{
int n = 5;
Console.Write(countUnsetBits(n));
}
}
// This code is contributed by Sanjit_Prasad
Javascript
输出:
4