數字中 0 和 1 的個數相同時,下一個大數字的二進位制表示是什麼?


比方說我們有一個二進位制數,它是數字 n 的表示。我們必須找到一個數的二進位制表示,它是最小的、但大於 n 的,並且具有相同數量的 0 和 1。所以,如果該數字是 1011(十進位制的 11),那麼結果將是 1101(十進位制的 13)。可以使用下一步排列計算找到這個問題的解。讓我們看看演算法,以瞭解這個想法。

演算法

nextBin(bin) −

Begin
   len := length of the bin
   for i in range len-2, down to 1, do
      if bin[i] is 0 and bin[i+1] = 1, then
         exchange the bin[i] and bin[i+1]
         break
      end if
   done
   if i = 0, then there is no change, return
   otherwise j:= i + 2, k := len – 1
   while j < k, do
      if bin[j] is 1 and bin[k] is 0, then
         exchange bin[j] and bin[k]
         increase j and k by 1
      else if bin[i] is 0, then
         break
      else
         increase j by 1
      end if
   done
   return bin
End

示例

#include <iostream>
using namespace std;
string nextBinary(string bin) {
   int len = bin.size();
   int i;
   for (int i=len-2; i>=1; i--) {
      if (bin[i] == '0' && bin[i+1] == '1') {
         char ch = bin[i];
         bin[i] = bin[i+1];
         bin[i+1] = ch;
         break;
      }
   }
   if (i == 0)
   "No greater number is present";
   int j = i+2, k = len-1;
   while (j < k) {
      if (bin[j] == '1' && bin[k] == '0') {
         char ch = bin[j];
         bin[j] = bin[k];
         bin[k] = ch;
         j++;
         k--;
      }
      else if (bin[i] == '0')
         break;
      else
         j++;
   }
   return bin;
}
int main() {
   string bin = "1011";
   cout << "Binary value of next greater number = " << nextBinary(bin);
}

輸出

Binary value of next greater number = 1101

更新於: 2019-08-20

238 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告