|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=1318 lang=golang |
| 3 | + * |
| 4 | + * [1318] 或运算的最小翻转次数 |
| 5 | + * |
| 6 | + * https://leetcode.cn/problems/minimum-flips-to-make-a-or-b-equal-to-c/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Medium (67.45%) |
| 10 | + * Likes: 61 |
| 11 | + * Dislikes: 0 |
| 12 | + * Total Accepted: 12.9K |
| 13 | + * Total Submissions: 19.1K |
| 14 | + * Testcase Example: '2\n6\n5' |
| 15 | + * |
| 16 | + * 给你三个正整数 a、b 和 c。 |
| 17 | + * |
| 18 | + * 你可以对 a 和 b 的二进制表示进行位翻转操作,返回能够使按位或运算 a OR b == c 成立的最小翻转次数。 |
| 19 | + * |
| 20 | + * 「位翻转操作」是指将一个数的二进制表示任何单个位上的 1 变成 0 或者 0 变成 1 。 |
| 21 | + * |
| 22 | + * |
| 23 | + * |
| 24 | + * 示例 1: |
| 25 | + * |
| 26 | + * |
| 27 | + * |
| 28 | + * 输入:a = 2, b = 6, c = 5 |
| 29 | + * 输出:3 |
| 30 | + * 解释:翻转后 a = 1 , b = 4 , c = 5 使得 a OR b == c |
| 31 | + * |
| 32 | + * 示例 2: |
| 33 | + * |
| 34 | + * 输入:a = 4, b = 2, c = 7 |
| 35 | + * 输出:1 |
| 36 | + * |
| 37 | + * |
| 38 | + * 示例 3: |
| 39 | + * |
| 40 | + * 输入:a = 1, b = 2, c = 3 |
| 41 | + * 输出:0 |
| 42 | + * |
| 43 | + * |
| 44 | + * |
| 45 | + * |
| 46 | + * 提示: |
| 47 | + * |
| 48 | + * |
| 49 | + * 1 <= a <= 10^9 |
| 50 | + * 1 <= b <= 10^9 |
| 51 | + * 1 <= c <= 10^9 |
| 52 | + * |
| 53 | + * |
| 54 | + */ |
| 55 | + |
| 56 | +package jzoffer |
| 57 | + |
| 58 | +import "fmt" |
| 59 | + |
| 60 | +// @lc code=start |
| 61 | +func minFlipsUsingString(a int, b int, c int) (res int) { |
| 62 | + trans := func(v int) string { |
| 63 | + return fmt.Sprintf("%032b", v) |
| 64 | + } |
| 65 | + sa, sb, sc := trans(a), trans(b), trans(c) |
| 66 | + for i := 0; i < len(sa); i++ { |
| 67 | + if sc[i] == '0' { |
| 68 | + if sa[i] == '1' { |
| 69 | + res++ |
| 70 | + } |
| 71 | + if sb[i] == '1' { |
| 72 | + res++ |
| 73 | + } |
| 74 | + continue |
| 75 | + } |
| 76 | + if sa[i] == '0' && sb[i] == '0' { |
| 77 | + res++ |
| 78 | + } |
| 79 | + } |
| 80 | + return |
| 81 | +} |
| 82 | + |
| 83 | +// 不用string, 位运算 |
| 84 | +func minFlips1(a int, b int, c int) (res int) { |
| 85 | + for i := 0; i < 32; i++ { |
| 86 | + // 1. c的第i位为0 |
| 87 | + if c&(1<<i) == 0 { |
| 88 | + // a的第i位为1 |
| 89 | + if a&(1<<i) != 0 { |
| 90 | + res++ |
| 91 | + } |
| 92 | + // b的第i位为1 |
| 93 | + if b&(1<<i) != 0 { |
| 94 | + res++ |
| 95 | + } |
| 96 | + continue |
| 97 | + } |
| 98 | + // 2. c的第i位为1 |
| 99 | + if a&(1<<i) == 0 && b&(1<<i) == 0 { |
| 100 | + res++ |
| 101 | + } |
| 102 | + } |
| 103 | + return |
| 104 | +} |
| 105 | + |
| 106 | +// @lc code=end |
0 commit comments