C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

C++での次の数値の2進表現


この問題では、数値の2進表現が与えられ、次の数の2進表現、つまり、与えられた数に1を足した後に得られる数を見つける必要があります。

バイナリ表現 数値の基数は、数値の基数を基数2に変更し、0または1のみを使用して数値を表します。

たとえば、14のバイナリ表現は1110です。

したがって、ここでは数値が与えられます。たとえば、バイナリ形式のnです。そして、n+1のバイナリ表現を見つける必要があります。

この問題を解決するには、2進加算の基本を知る必要があります。 1をバイナリ形式で0または1に追加するとどうなるか見てみましょう。

0 + 1 =1

1 + 1 =10

上記の問題を解決する方法の例を見てみましょう。

Input: 010010111
Output: 010011000
Explanation : (010010111)2 is the binary representation of 152 and the next number will be 153 
whose binary representation is (010011000)2. We will use binary addition here and add binary (1)2 
to the binary representation of the number.

上記の例から、数値に2進数1を追加すると、最初の0が検出され、この0が1に反転するまで、右から始まるすべての1が0に変換されることがわかります。次に、このロジックのアルゴリズムを作成しましょう。

アルゴリズム

Step 1 : Start right to left i.e n-1 to 0
Step 2 : If 0 is encountered, change it 1 and break
Step 3 : If one is encounter change it to 0.
Step 4 : When no zero is encountered, add 1 to the start of the array.
Step 5 : Print the array.

それでは、このアルゴリズムのコード実装を見てみましょう。

#include <bits/stdc++.h>
using namespace std;
string nextBinary(string num) {
   int l = num.size();
   int flag = 0 ;
   for (int i=l-1; i>=0; i--) {
      if (num.at(i) == '0') {
         num.at(i) = '1';
         flag = 1;
         break;
      } else
         num.at(i) = '0';
   }
   if (flag < 0)
      num = "1" + num;
   return num;
}
int main() {
   string number = "0111010111";
   cout<<"The Binary representation of the number is "<<number<<endl;
   cout<<"Binary representation of next number is "<<nextBinary(number);
   return 0;
}

出力

The Binary representation of the number is 0111010111
Binary representation of next number is 0111011000

  1. C++五胞体数

    五胞体数は、パスカルの三角形の5番目の数として表されます。ご存知のように、これは5番目の数字です。つまり、パスカルの三角形に少なくとも5つの数字が必要です。したがって、このシリーズの最初の数字は 1 4 6 4 1から始まります。 パスカルの三角形の4行目。したがって、このチュートリアルでは、たとえば、n番目の五胞体数を見つける必要があります Input : 1 Output : 1 Input : 4 Output : 35 次の図から出力を確認できます- この問題については、可能な限り、これは一種のシリーズであるため、ソリューションでこのシリーズのパターンを見つけようと

  2. C++の二分探索木イテレータ

    二分木用に1つのイテレータを作成するとします。 2つの方法があります。 next()メソッドは次の要素を返し、hasNext()メソッドはブール値を返します。これは次の要素が存在するかどうかを示します。したがって、ツリーが次のような場合- そして、関数呼び出しのシーケンスは、[next()、next()、hasNext()、next()、hasNext()、next()、hasNext()、next()、hasNext()]です。出力は[3,7、true、9、true、15、true、20、false]になります これを解決するには、次の手順に従います- nextとhasNextの