C++ 中统计与 N 的差值等于与 N 的异或值的数字


我们有一个数字 N。目标是在 0 到 N 之间找到与 N 的差值等于与 N 的异或值的数字。

我们将通过遍历从 i=0 到 i<=N 的数字来实现这一点,对于每个 i,如果 (N-X==i^N),则递增计数。

让我们通过示例来理解。

输入 − X=6

输出 − 与 N 的差值等于与 N 的异或值的数字的计数:4

解释 − 数字为 0 2 4 6。

输入 − X=20

输出 − 与 N 的差值等于与 N 的异或值的数字的计数:4

解释 − 数字为 0 4 16 20

下面程序中使用的方案如下

  • 我们取整数 N。

  • 函数 diffisXOR(int n) 获取 n 并返回与 n 的差值等于与 n 的异或值的数字的计数。

  • 将初始计数设为 0。

  • 从 i=0 遍历到 i<=n。

  • 如果 i-n==i^n。递增计数

  • 在 for 循环结束时,计数将具有所需的结果。

  • 返回并打印计数。

示例

#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int diffisXOR(int n){
   int count = 0;
   for (int i = 0; i <= x; i++){
      if((x-i)==(i^x))
         { count++; }
   }
   return count;
}
int main(){
   int N = 15;
   int nums=diffisXOR(N);
   cout <<endl<<"Count of numbers whose difference with N == XOR with N: "<<nums;
   return 0;
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

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

Count of numbers whose difference with N == XOR with N: 16

更新于: 2020-10-31

104 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告