C++でビット単位のOrがKに等しいN個の異なる数を検索します
コンセプト
与えられた2つの整数NとKに関して、私たちのタスクは、ビット単位のORがKに等しいN個の異なる整数を決定することです。可能な答えが存在しない場合は、-1を出力することがわかっています。
入力
N = 4, K = 6
出力
6 0 1 2
入力
N = 11, K = 6
出力
-1
解決策を見つけることはできません。
メソッド
-
数列のビット単位のORがKである場合、Kで0であるすべてのビットインデックスもすべての数でゼロでなければならないことを私たちは知っています。
-
この結果、ビットがKの1である場合に変更できる位置のみがあります。そのカウントをBit_Kとします。
-
現在、Bit_Kビットでpow(2、Bit_K)個の異なる数値を作成できます。この結果、1つの数値をK自体として扱う場合、残りのN – 1の数値は、Kで0であるすべての数値のすべてのビットを0に設定し、他のビット位置ではBit_Kビット以外の任意の順列を設定することで構築できます。番号K。
-
pow(2、Bit_K)
例
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define MAX1 32
ll pow2[MAX1];
bool visited1[MAX1];
vector<int> ans1;
// Shows function to pre-calculate
// all the powers of 2 upto MAX
void power_2(){
ll ans1 = 1;
for (int i = 0; i < MAX1; i++) {
pow2[i] = ans1;
ans1 *= 2;
}
}
// Shows function to return the
// count of set bits in x
int countSetBits(ll x1){
// Used to store the count
// of set bits
int setBits1 = 0;
while (x1 != 0) {
x1 = x1 & (x1 - 1);
setBits1++;
}
return setBits1;
}
// Shows function to add num to the answer
// by placing all bit positions as 0
// which are also 0 in K
void add(ll num1){
int point1 = 0;
ll value1 = 0;
for (ll i = 0; i < MAX1; i++) {
// Bit i is 0 in K
if (visited1[i])
continue;
else {
if (num1 & 1) {
value1 += (1 << i);
}
num1 /= 2;
}
}
ans1.push_back(value1);
}
// Shows function to find and print N distinct
// numbers whose bitwise OR is K
void solve(ll n1, ll k1){
// Choosing K itself as one number
ans1.push_back(k1);
// Find the count of set bits in K
int countk1 = countSetBits(k1);
// It is not possible to get N
// distinct integers
if (pow2[countk1] < n1) {
cout << -1;
return;
}
int count1 = 0;
for (ll i = 0; i < pow2[countk1] - 1; i++) {
// Add i to the answer after
// placing all the bits as 0
// which are 0 in K
add(i);
count1++;
// Now if N distinct numbers are generated
if (count1 == n1)
break;
}
// Now print the generated numbers
for (int i = 0; i < n1; i++) {
cout << ans1[i] << " ";
}
}
// Driver code
int main(){
ll n1 = 4, k1 = 6;
// Pre-calculate all
// the powers of 2
power_2();
solve(n1, k1);
return 0;
} 出力
6 0 1 2
-
合計とGCDがC++で与えられている2つの数値を見つけます
2つの数aとbの合計とgcdがあります。数字aとbの両方を見つける必要があります。それが不可能な場合は、-1を返します。合計が6でgcdが2であるとすると、数値は4と2になります。 このアプローチは、GCDが与えられると、その数がその倍数になることが知られているようなものです。次の手順があります 最初の数値をGCDとして選択すると、2番目の数値はsum − GCDになります。 前の手順で選択した数値の合計が合計と同じである場合は、両方の数値を出力します。 それ以外の場合は、数値が存在しないため、-1を出力します。 例 #include <iostream>
-
Pythonでビット単位のOrがKに等しいN個の異なる数を検索します
2つの整数NとKがあるとします。ビット単位のORがKと同じN個の一意の値を見つける必要があります。そのような結果がない場合は、-1を返します したがって、入力がN=4およびK=6の場合、出力は[6,0,1,2]になります。 これを解決するには、次の手順に従います- MAX:=32 訪問:=サイズMAXのリストとFalseで埋める res:=新しいリスト 関数add()を定義します。これにはnumがかかります ポイント:=0 値:=0 0からMAXの範囲のiの場合、実行 visited [i]がゼロ以外の場合、 次のイテレーションに行