在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

更新於:2021年3月16日

1K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.