C++での前の数値の2進表現
この問題では、数値の2進表現が与えられ、前の数の2進表現、つまり、与えられた数から1を引いた後に得られる数を見つける必要があります。
バイナリ表現 数値の基数は、数値の基数を基数2に変更し、0または1のみを使用して数値を表します。
たとえば、23のバイナリ表現は10111です。
したがって、ここでは数値が与えられます。たとえば、バイナリ形式のnです。そして、n-1のバイナリ表現を見つける必要があります。
この問題を解決するには、バイナリ減算の基本を知る必要があります。 1がバイナリ形式で0または1から減算されたときに何が起こるかを見てみましょう。0-1=1+1次のビットからのキャリー。 1-1=0。
問題をよりよく理解するために例を見てみましょう。
Input : 101101100 Output : 101101011 Explanation : (101101100)2 Is the binary representation of 364. The number preceding it is 363 whose binary representation is (101101011)2 . we have used binary subtraction here and subtracted (1)2 from the binary representation of the number to yield the result .
このプログラムの背後にあるロジックを見てから、そのロジックに基づいてアルゴリズムを設計します。ここでは、数値の2進表現から1を引く必要があります。このために、右から開始し、1が検出されるまで、すべてのゼロを1に反転します。 1が検出されると、1を0に反転し、最終結果を返します。
Step 1 : Start right to left i.e n-1 to 0. Step 2 : If 1 is encounter change it to 0 and break. Step 3 : If 0 is encountered, change it 1. Step 4 : Print the array.
例
上記のアルゴリズムのプログラム実装-
#include <bits/stdc++.h>
using namespace std;
string previousNumber(string num) {
int n = num.size();
if (num.compare("1") == 0)
return "0";
int i;
for (i = n - 1; i >= 0; i--) {
if (num.at(i) == '1') {
num.at(i) = '0';
break;
} else
num.at(i) = '1';
}
if (i == 0)
return num.substr(1, n - 1);
return num;
}
int main() {
string number = "1011011000";
cout<<"the Binary representation of the number is "<<number<<endl;
cout<<"Binary representation of previous number is "<<previousNumber(number);
return 0;
} 出力
The Binary representation of the number is 1011011000 Binary representation of previous number is 1011010111
-
他の累乗での数値のC++表現
別の数の累乗で数を表す問題について話し合います。 xとyの2つの数字が与えられます。たとえば、yをxの累乗で表すことができるかどうかを判断する必要があります。たとえば、xの各累乗を1回使用できます。 Input: x = 4, y = 11 Output: true Explanation: 4^2 - 4^1 - 4^0 = 11 Hence y can be represented in the power of x. Input: x = 2, y = 19 Output: true Explanation: 2^4 + 2^1 + 2^0 =19 Hence y can be rep
-
C++五胞体数
五胞体数は、パスカルの三角形の5番目の数として表されます。ご存知のように、これは5番目の数字です。つまり、パスカルの三角形に少なくとも5つの数字が必要です。したがって、このシリーズの最初の数字は 1 4 6 4 1から始まります。 パスカルの三角形の4行目。したがって、このチュートリアルでは、たとえば、n番目の五胞体数を見つける必要があります Input : 1 Output : 1 Input : 4 Output : 35 次の図から出力を確認できます- この問題については、可能な限り、これは一種のシリーズであるため、ソリューションでこのシリーズのパターンを見つけようと