diff options
author | Jack Sangdahl <[email protected]> | 2024-09-10 18:07:32 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2024-09-10 18:07:32 -0600 |
commit | 309241c48abc953042965d0735e17f098c426105 (patch) | |
tree | d0ab51abebb4650cd8781e1d038f1140b9c638ef | |
parent | 628024d350e3769cb86aaadc1043d9aaf452de3c (diff) | |
download | leetcode-309241c48abc953042965d0735e17f098c426105.tar.gz leetcode-309241c48abc953042965d0735e17f098c426105.zip |
2220. minimum bit flips to convert number
-rw-r--r-- | min_bit_flips_convert_num.c | 18 | ||||
-rw-r--r-- | min_bit_flips_convert_num.py | 24 |
2 files changed, 42 insertions, 0 deletions
diff --git a/min_bit_flips_convert_num.c b/min_bit_flips_convert_num.c new file mode 100644 index 0000000..2f49b3b --- /dev/null +++ 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 new file mode 100644 index 0000000..6b5da6f --- /dev/null +++ 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)) |