Cプログラムで同じ数の1と0を持つ次に大きい数の2進表現?
1つの2進数、つまり数値nの表現があるとします。最小でnより大きい数のバイナリ表現を見つける必要があり、0と1の数も同じです。したがって、数値が1011(10進数で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
-
バイナリ表現が回文であるかどうかをチェックするPythonプログラム?
ここでは、さまざまなpython組み込み関数を使用します。まず、bin()を使用して数値を2進数に変換し、次に2進数形式の文字列を逆にして、元の文字列と比較します。一致する場合は回文、そうでない場合は回文です。 例 Input: 5 Output: palindrome 説明 5のバイナリ表現は101です それを逆にすると、結果は101になり、オリジナルと比較して一致します。 したがって、その回文 アルゴリズム Palindromenumber(n) /* n is the number */ Step 1: input n Step 2: convert n into binar
-
2つの数値の2進表現がアナグラムであるかどうかをチェックするPythonプログラム。
与えられた2つの数字。私たちの仕事は、それらがバイナリ表現でお互いのアナグラムであるかどうかを確認することです。カウンター(反復可能)メソッドと辞書比較を使用して、Pythonでこの問題をすばやく解決できます。 例 Input: a = 8, b = 16 Output : Yes Binary representations of both numbers have same 0s and 1s. アルゴリズム Step 1 : Given two numbers. Step 2 : Convert both number into its binary using bin() fu