commit 309241c48abc953042965d0735e17f098c426105
parent 628024d350e3769cb86aaadc1043d9aaf452de3c
Author: Jack Sangdahl <jack@pngu.org>
Date: Tue, 10 Sep 2024 18:07:32 -0600
2220. minimum bit flips to convert number
Diffstat:
2 files changed, 42 insertions(+), 0 deletions(-)
diff --git a/min_bit_flips_convert_num.c b/min_bit_flips_convert_num.c
@@ -0,0 +1,18 @@
+// 2220. Minimum Bit Flips to Convert Number
+#include "leetcode.h"
+
+/*
+ * a bit flip of a number 'x' is choosing a bit in the binary representation of
+ * 'x' and flipping it from either 0 to 1 or 1 to 0. given two integers 'start'
+ * and 'goal', return the minimum number of bit flips to convert 'start' to
+ * 'goal'.
+ */
+
+int minBitFlips(int start, int goal) {
+ return __builtin_popcount(start ^ goal);
+}
+
+int main() {
+ printf("%d\n", minBitFlips(10, 7)); // expect: 3
+ printf("%d\n", minBitFlips(3, 4)); // expect: 3
+}
diff --git a/min_bit_flips_convert_num.py b/min_bit_flips_convert_num.py
@@ -0,0 +1,24 @@
+# 2220. Minimum Bit Flips to Convert Number
+
+"""
+a bit flip of a number 'x' is choosing a bit in the binary representation of
+'x' and flipping it from either 0 to 1 or 1 to 0. given two integers 'start'
+and 'goal', return the minimum number of bit flips to convert 'start' to
+'goal'.
+"""
+
+
+class Solution(object):
+ def minBitFlips(self, start, goal):
+ """
+ :type start: int
+ :type goal: int
+ :rtype: int
+ """
+ return (start ^ goal).bit_count()
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minBitFlips(10, 7))
+ print(obj.minBitFlips(3, 4))