在C++中查找唯一设置位的位 置
在这个问题中,我们得到一个数字N,它的二进制表示中只有一个设置位。我们的任务是找到唯一设置位的位 置。如果数字只有一个设置位,则返回数字的位 置,否则打印无效数字。
让我们举个例子来理解这个问题:
输入
N = 32
输出
6
解释
Binary representation of the number is 10000.
解决方案方法
在我们继续之前,需要知道一个事实:如果一个数字是2的幂,则它只有一个设置位。否则,它将有多个设置位。
一个简单的解决方案是从最右边的位开始,然后检查位的数值。我们将使用循环来检查它是否已设置。
程序说明了我们解决方案的工作原理:
示例
#include <iostream>
using namespace std;
bool isPowerOfTwo(unsigned n) {
if(n>0) {
while(n%2 == 0)
n/=2;
if(n == 1)
return true;
}
if(n == 0 || n != 1)
return false;
return false;
}
int findPostionOfSetBit(unsigned n) {
unsigned i = 1, position = 1;
while (!(i & n)) {
i = i << 1;
++position;
}
return position;
}
int main(void){
int n = 64;
if(!isPowerOfTwo(n))
cout<<"Invalid Number!";
else
cout<<"The position of the number "<<n<<" is "<<findPostionOfSetBit(n);
return 0;
}输出
The position of the number 64 is 7
解决这个问题的另一种方法是使用移位操作将数字向右移位,直到它变为0。最后,达到0所做的移位次数就是设置位的位 置。
程序说明了我们解决方案的工作原理:
示例
#include <iostream>
using namespace std;
bool isPowerOfTwo(unsigned n) {
if(n>0) {
while(n%2 == 0)
n/=2;
if(n == 1)
return true;
}
if(n == 0 || n != 1)
return false;
return false;
}
int findPostionOfSetBit(unsigned n) {
unsigned position = 0;
while (n) {
n = n >> 1;
++position;
}
return position;
}
int main(void){
int n = 64;
if(!isPowerOfTwo(n))
cout<<"Invalid Number!";
else
cout<<"The position of the number "<<n<<" is
"<<findPostionOfSetBit(n);
return 0;
}输出
The position of the number 64 is 7
还有一种方法可以使用数学公式来解决这个问题。我们知道:
2i = n, where n is the number and i is the position of the number The values of i here can be found using the formula, i = log2(n)
程序说明了我们解决方案的工作原理:
示例
#include <iostream>
#include <math.h>
using namespace std;
bool isPowerOfTwo(unsigned n) {
if(n>0) {
while(n%2 == 0)
n/=2;
if(n == 1)
return true;
}
if(n == 0 || n != 1)
return false;
return false;
}
int findPostionOfSetBit(unsigned n) {
unsigned position = log2(n) + 1; ;
return position;
}
int main(void){
int n = 64;
if(!isPowerOfTwo(n))
cout<<"Invalid Number!";
else
cout<<"The position of the number "<<n<<" is "<<findPostionOfSetBit(n);
return 0;
}输出
The position of the number 64 is 7
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP