C++中求和与异或相等


在这个问题中,我们给定一个整数n。我们的任务是创建一个程序来查找从i = 0到n的整数的计数,其中sum等于XOR,即(n+i) = (n^i)

让我们举个例子来理解这个问题:

输入: n = 4

输出:4

解释:

考虑从0到n的所有i值:

i = 0, 4 + 0 = 4, 4^0 = 4
i = 1, 4 + 1 = 5, 4^1 = 5
i = 2, 4 + 2 = 6, 4^2 = 6
i = 3, 4 + 3 = 7, 4^3 = 7
i = 4, 4 + 4 = 8, 4^4 = 0
计数 = 4

解决方案方法

一个简单的解决方案是找到n和i的和以及n和i的异或的值。比较这两个值,然后计算它们相等的值。

算法

步骤1:循环遍历i = 0到n的所有值。

步骤1.1:找到(n + i)的值。

步骤1.2:找到(n^i)的值。

步骤1.3:比较步骤1.1和1.2中找到的值。
步骤1.4:如果它们相等,则增加计数。

步骤2:打印计数值。

程序说明了我们解决方案的工作原理:

示例

在线演示

#include <iostream>
using namespace std;

int main() {
   
   int n = 5;
   int counter = 0;
   for(int i=0; i<=n; i++ )
      if ( (n+i) == (n^i) )
         counter++;
   cout<<"The count of integers with equal sum and XOR is "<<counter;
   return 0;
}

输出:

The count of integers with equal sum and XOR is 2

此方法很好,但该问题可能存在更好的解决方案,即使用以下事实:

如果 n^i = n+i,则 n&i = 0

如果n&i = 0,我们需要这两个数字具有相反的设置和未设置位。我们需要计算这样的值。这是一个执行此操作的程序:

示例

在线演示

#include <iostream>
using namespace std;

int countValuesWithEqualSumXOR(int n) {
   
   int countUnSetBits=0;
   while (n) {
      if ((n & 1) == 0)
         countUnSetBits++;
      n=n>>1;
   }
   return 1 << countUnSetBits;
}

int main()
{
   int n = 6;
   cout<<"The count of integers with equal sum and XOR is "<<countValuesWithEqualSumXOR(n);
   return 0;
}

输出:

The count of integers with equal sum and XOR is 2

更新于:2021年1月22日

758 次查看

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.