mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
problems(cpp): add “1318. Minimum Flips to Make a OR b Equal to c”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
2bf902b161
commit
c74dc48221
1 changed files with 38 additions and 0 deletions
38
problems/cpp/minimum-flips-to-make-a-or-b-equal-to-c.cpp
Normal file
38
problems/cpp/minimum-flips-to-make-a-or-b-equal-to-c.cpp
Normal file
|
@ -0,0 +1,38 @@
|
|||
#include <cassert>
|
||||
#include <tuple>
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int minFlips(int a, int b, int c)
|
||||
{
|
||||
auto flips = 0;
|
||||
|
||||
for (; (a | b) != c; a >>= 1, b >>= 1, c >>= 1) {
|
||||
auto [aa, bb, cc] = std::tuple { a & 1, b & 1, c & 1 };
|
||||
|
||||
if ((aa | bb) == cc) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (aa && bb) {
|
||||
flips += 2;
|
||||
} else {
|
||||
flips++;
|
||||
}
|
||||
}
|
||||
|
||||
return flips;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
Solution s;
|
||||
|
||||
assert(s.minFlips(2, 6, 5) == 3);
|
||||
assert(s.minFlips(4, 2, 7) == 1);
|
||||
assert(s.minFlips(1, 2, 3) == 0);
|
||||
assert(s.minFlips(8, 3, 5) == 3); // 1000 | 0011 = 0101
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue