vc++ 二进制文件的查找_在C ++中查找表示二进制数所需的总位数

这篇博客介绍了如何使用位操作技术在C++中计算表示一个数字所需的二进制位数。通过不断右移数字直到结果为零,右移的总次数即为所需的位数。文中给出了示例和程序代码。
摘要由CSDN通过智能技术生成

vc++ 二进制文件的查找

Problem statement:

问题陈述:

Find total Number of bits required to represent a number in binary

查找以二进制表示数字所需的总位数

Example 1:

范例1:

    input : 10
    output: 4

Example 2:

范例2:

    input  : 32
    output : 6

Explanation:

说明:

input       Binary representation          count of bits
10               1010                        4
32              100000                       6

We can count required number of bits to represent a number using many ways; here we are using Bit manipulation technique to do the same.

我们可以使用多种方法来计算表示一个数字所需的位数 。 在这里,我们使用位操作技术来执行相同的操作。

We will right shift ( >> ) a number by one place in each iteration until we get zero as result. And, total count of right shift ( >> ) operation will be our result.

我们将在每次迭代中将数字( >> )右移一位,直到结果为零。 并且,右移( >> )运算的总数将是我们的结果。

Example:

例:

Let Number = 45 ( 101101 in binary)

shifting 45 to right by 1 place
45 >> 1 = ( 101101 ) >> 1 = ( 10110 ) =  22 in decimal

so n= 22  ( 10110 in binary )
Again shifting 22 to right by 1 place
22 >> 1 = ( 10110 ) >> 1 = ( 1011 ) =  11  in decimal

now n= 11
Again shifting 11 to right by 1 place
11 >> 1 = ( 1011 ) >> 1 = ( 101 ) = 5 in decimal

now n= 5
Again shifting 5 to right by 1 place
5 >> 1 = ( 101 ) >> 1 = ( 10 ) = 2 in decimal

now n=2
Again shifting 2 to right by 1 place
2 >> 1 = ( 10 ) >> 1 = ( 1 ) = 1 in decimal

now n=1
Again shifting 1 to right by 1 place
1 >> 1 = ( 1 ) >> 1 = ( 0 )= 0 in decimal

Here we got n=0
So we will stop.

As u can see we have used total 6 right shift operation ( >> ) to get 0, so 6 will be required number of minimum bits to represent a number in binary.

如您所见,我们总共使用了6个右移运算(>>)来获得0,所以将需要6个最小位数来表示二进制数。

Program:



程序:

</ s> </ s> </ s>
#include<bits/stdc++.h>
using namespace std;

int countBits(int n)
{
	int count=0;
	// While loop will run until we get n = 0
	while(n)
	{
		count++;
		// We are shifting n to right by 1 
		// place as explained above
		n=n>>1;
	}
	return count;
}


int main()
{
	int n;
	cout << "Enter any Number\n";
	cin >> n;
	int count=countBits(n);
	cout << "Number of bits : " << count ;
	return 0;
}

Output

输出量

Enter any Number
45
Number of bits : 6
Process returned 0 (0x0)   execution time : 1.721 s
Press any key to continue.


翻译自: https://www.includehelp.com/cpp-programs/find-total-number-of-bits-required-to-represent-a-number-in-binary.aspx

vc++ 二进制文件的查找

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值