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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP