__builtin_popcount = int __builtin_popcountl = longint __builtin_popcountll = longlong
例子:
1 2 3 4 5 6 7 8 9 10 11
// C++ code to demonstrate the // __builtin_popcount function #include<bits/stdc++.h> usingnamespace std; intmain() { int n = 4; // Printing the number of set bits in n cout << __builtin_popcount(n); return0; }
输出
1
1
时间复杂度(b),其中b是位数。
辅助空间:O(1)
1 2 3 4 5 6 7
classSolution { public: intminChanges(int n, int k){ if ((n & k) != k) return-1; return __builtin_popcount(n ^ k); } };
classSolution { public: intmaxOperations(string s){ int n = s.size(); int res = 0; int ans = 0; for (int i = 0; i < n; ++i) { if (s[i] == '1') { ans++; } elseif (i && s[i - 1] == '1') { res += ans; } }
classSolution { public: intminNumberOperations(vector<int>& target){ int n = target.size(); int ans = target[0]; for (int i = 1; i < n; ++i) { ans += max(target[i] - target[i - 1], 0); } return ans; } };
classSolution { public: longlongminimumOperations(vector<int>& nums, vector<int>& target){ int n = nums.size(); longlong det[n]; for (int i = 0; i < n; i++) det[i] = target[i] - nums[i]; auto sgn = [&](longlong x) { if (x == 0) return0; if (x > 0) return1; return-1; }; auto jisuan = [&](int l, int r) { longlong ret = 0, last = 0; for (int i = l; i <= r; i++) { if(i==l) { ret+=abs(det[i]); } else { ret += max((longlong)(abs(det[i]) - abs(det[i - 1])), 0ll); } }
return ret; };
longlong ans = 0; for (int i = 0, j = 0; i < n; i++) { if (i == n - 1 || sgn(det[i + 1]) != sgn(det[j])) { ans += jisuan(j, i); j = i + 1; } } return ans; } };