intmain() { int t; cin >> t; while (t--) { int x; cin >> x; int ans = 0; while (x > 0) { x -= lowbit(x); ans++; } cout << ans << " "; }
return0; }
异或运算的性质
1 2 3 4
//(1) 异或运算是无进位相加 //(2) 异或运算满足交换律和结合律 //(3) 0 ^ n = n, n ^ n = 0 //(4) 整体异或和如果为x, 整体中某部分异或和如果为y, 那么剩下部分的异或和为x ^ y
交换两个数
1 2 3 4 5 6 7 8 9 10 11 12
voidsolve() { int a, b; cin >> a >> b; //不妨我们设a = A, b = B; a = a ^ b; //a = A ^ B; b = a ^ b; //b = (A ^ B) ^ B = A ^ (B ^ B) = A; a = a ^ b; //a = (A ^ B) ^ A = B ^ (A ^ A) = B; cout << "a = " << a << endl; cout << "b = " << b << endl; //用这种方法交换两个位置的数一定要保证不在同一位置 }
voidsolve() { int a, b; cin >> a >> b; int c = a - b; cout << "c = " << c << endl; int returnA = filp(sign(c)); int returnB = sign(c); cout << "returnA = " << returnA << endl; cout << "returnB = " << returnB << endl; int ans = a * returnA + b * returnB; cout << "max = " << ans << endl; }
找到缺失的数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
voidsolve() {
//0 - n中缺了一个数 //找到缺的那个数是什么 int n; cin >> n; vector<int> arr(n); int sum1 = 0; int sum2 = n; for (int i = 0; i < n; i++) { cin >> arr[i]; sum1 ^= arr[i]; sum2 ^= i; } int ans = sum1 ^ sum2; cout << ans << endl; }
找到出现了奇数次的数
1 2 3 4 5 6 7 8 9 10 11 12 13 14
voidsolve() { //数组中有一个数出现的次数为奇数,其他所有的数都出现了偶数次 //请找出那个出现了奇数次的那个数 int n; cin >> n; vector<int> arr(n); int ans = 0; for (int i = 0; i < n; i++) { cin >> arr[i]; ans ^= arr[i]; } cout << ans << endl; }
#include<bits/stdc++.h> #define int long long usingnamespace std;
voidsolve() { int l, r; int ans = 0; cin >> l >> r; // ans = 高位相同的部分 + 后面一部分全部取值为1 int x = r; int d = -1; while (x) { d++; x >>= 1; } int i; for (i = d; i >= 0; i--) { // 获取第 i 位 int t1 = (l >> i) & 1; int t2 = (r >> i) & 1; if (t1 == t2) { ans += t1 * (1LL << i); } else { break; } } if (i >= 0) ans += (1LL << (i + 1)) - 1; cout << ans << endl; }
signedmain() { ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t = 1; cin >> t; while(t--){ solve(); } return0; }