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;
}輸出
如果我們執行以上程式碼,它將生成以下輸出:
Count of numbers whose difference with N == XOR with N: 16
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP