标签:span 运算 count 数字 turn code 出现 根据 for
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;
标签:span 运算 count 数字 turn code 出现 根据 for
原文地址:https://www.cnblogs.com/asenyang/p/12182127.html