x <= n的值计数,其中C ++中(n XOR x)=(n – x)

给定数字n作为输入。目标是找到满足条件(n xor x)=(nx)的值x。x也在[0,n]范围内。

让我们用例子来理解

输入-n = 10

输出-x <= n的值计数,其中(n XOR x)=(n – x)为− 4

解释-10或x = 10-x − 0、2、8和10的x的值。

输入-n = 15

输出-x <= n的值计数,其中(n XOR x)=(n – x)为-16

解释-具有15个x或x = 15-x的x值-0、1、2、3、4、5、6、7、8、9、10、11、12、13、14和15

以下程序中使用的方法如下

我们将使用两种方法。第一种使用for循环的天真方法。对于i,尽可能从i = 0开始遍历到i <= n。现在检查是否(n-i ==(n ^ i)// xor)。如果为真,则递增计数。

  • 以整数变量n作为输入。

  • 函数unique_pair(int arr [],int size)接受数组及其长度,并返回唯一对的数量,使得成对(arr [i],arr [j])中的索引i <j

  • 将count的初始值设为0。

  • 取一个包含整数对的“ se”集。(set <pair <int,int >> se)

  • 使用两个for循环开始遍历arr []。从i = 0到i <size-1,从j = i + 1到j <size。

  • 对于每对总是i <j,使用se.insert(make_pair(arr [i],arr [j]))将对(arr [i],arr [j])添加到'se'。

  • 在两个for循环的末尾,更新count = se.size()。

  • Count现在在“ se”中有许多对。(所有都是唯一的)。

  • 返回计数作为结果。

高效方法

在这种方法中,我们将首先将n转换为其等效的二进制数。我们知道

1 xor 0 = 1-0

1 xor 1 = 1-1

0 xor 0≠0-1

0 xor 1≠0-1

因此,对于n的二进制表示形式中的每1,有2种情况。对于以n的二进制表示形式的p个,将有2p个满足条件的值。

索引 然后,将这样的计数相加,得出总的唯一对。

  • 以整数变量n作为输入。

  • 函数unique_pair(int arr [],int size)接受数组及其长度,并返回唯一对的数量,使得成对(arr [i],arr [j])中的索引i <j

  • 将count的初始值设为0。

  • 使用number = bitset <8>(n).to_string();将n转换为字符串

  • 取length = number.length()。

  • 使用for循环从索引i = 0到i <length遍历字符串。每增加1计数。

  • 将count = pow(2,count)设置为x的最终值。

  • 返回计数作为结果。

示例(幼稚的方法)

#include<bits/stdc++.h>
using namespace std;
int count_values(int n){
   int count = 0;
   for (int i = 0; i <= n; i++){
      if (n - i == (n ^ i)){
         count++;
      }
   }
   return count;
}
int main(){
   int n = 25;
   cout<<"Count of values of x <= n for which (n XOR x) = (n – x) are: "<<count_values(n);
   return 0;
}

输出结果

如果我们运行上面的代码,它将生成以下输出-

Count of values of x <= n for which (n XOR x) = (n – x) are: 8

示例(有效方法)

#include<bits/stdc++.h>
using namespace std;
int count_values(int n){
   int count = 0;
   string number = bitset<8>(n).to_string();
   int length = number.length();
   for (int i = 0; i < length; i++){
      if (number.at(i) == '1')
         { count++; }
   }
   count = (int)pow(2, count);
   return count;
}
int main(){
   int n = 25;
   cout<<"Count of values of x <= n for which (n XOR x) = (n – x) are: "<<count_values(n);
   return 0;
}

输出结果

如果我们运行上面的代码,它将生成以下输出-

Count of values of x <= n for which (n XOR x) = (n – x) are: 8
猜你喜欢