首页 > 其他 > 详细

leetcode1318

时间:2020-01-12 11:37:17      阅读:85      评论:0      收藏:0      [点我收藏+]
 1 class Solution:
 2     def converToBin(self,n):
 3         N = [0] * 32
 4         i = 31
 5         while n != 0:
 6             r = n % 2
 7             N[i] = r
 8             i -= 1
 9             n = n // 2
10         return N
11     def minFlips(self, a: int, b: int, c: int) -> int:
12         A,B,C = self.converToBin(a),self.converToBin(b),self.converToBin(c)
13         #print(A,B,C)
14         count = 0
15         for i in range(31,-1,-1):
16             bit_a,bit_b,bit_c = A[i],B[i],C[i]
17             if bit_c == 0:
18                 if bit_a == 1:
19                     count += 1
20                 if bit_b == 1:
21                     count += 1
22             else:#bit_c == 1
23                 if bit_a == 0 and bit_b == 0:
24                     count += 1
25         return count

算法思想:位运算。根据按位与的运算规则:0 | 0 = 0    0 | 1 = 1    1 | 0 = 1    1 | 1 = 1。

先将数字转化为32位的二进制表示。然后对应位置进行比较。

要得到0,需要将所有的1都转化成0;

要得到1,需要至少出现一次1;

leetcode1318

原文:https://www.cnblogs.com/asenyang/p/12182127.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!