查找 C++ 中唯一设置位的位置
在这个问题中,我们给出了一个数字N,它的二进制表示中只有一个设置位。我们的任务是找到唯一设置位的位置。如果数字只有一个设置位,则返回数字的位置,否则打印无效数字。
让我们举个例子来理解这个问题,
输入
N = 32输出结果
6
解释
Binary representation of the number is 10000.
解决方法
在我们进一步进行之前要知道的一个事实是,如果它是2的幂,则该数字将只有1个设置位。否则它将具有更多的设置位。
一个简单的解决方案是从最右边的位开始,然后检查位的值。我们将使用循环来检查它是否已设置。
程序来说明我们的解决方案的工作,
示例
#includeusing 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<<"无效号码!"; else cout<<"号码的位置 "< 输出结果 号码的位置 64 is 7解决该问题的另一种方法是使用移位操作将数字右移直到它变为0。最后达到0的移位次数是设置位的位置。
程序来说明我们的解决方案的工作,
示例
#includeusing 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<<"无效号码!"; else cout<<"号码的位置 "< 输出结果 号码的位置 64 is 7解决问题的另一种方法是使用数学公式。我们知道,
2i = n, where n is the number and i is 号码的位置 The values of i here can be found using the formula, i = log2(n)程序来说明我们的解决方案的工作,
示例
#include#include 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<<"无效号码!"; else cout<<"号码的位置 "< 输出结果 号码的位置 64 is 7