zoukankan      html  css  js  c++  java
  • 【leetcode】1318. Minimum Flips to Make a OR b Equal to c

    题目如下:

    Given 3 positives numbers ab and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).
    Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.

    Example 1:

    Input: a = 2, b = 6, c = 5
    Output: 3
    Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)

    Example 2:

    Input: a = 4, b = 2, c = 7
    Output: 1
    

    Example 3:

    Input: a = 1, b = 2, c = 3
    Output: 0

    Constraints:

    • 1 <= a <= 10^9
    • 1 <= b <= 10^9
    • 1 <= c <= 10^9

    解题思路:本题很简单。如果c某一位是0,那么需要a和b相应的那一位都是0,翻转次数为a和b相应位1的个数;如果c的某位是1,那么只有a和b对应位都是0的情况下做两次翻转。

    代码如下:

    class Solution(object):
        def minFlips(self, a, b, c):
            """
            :type a: int
            :type b: int
            :type c: int
            :rtype: int
            """
            res = 0
            na = bin(a)[2:].rjust(32, '0');
            nb = bin(b)[2:].rjust(32, '0');
            nc = bin(c)[2:].rjust(32, '0');
    
            for i in range(32):
                ia,ib,ic = int(na[i]),int(nb[i]),int(nc[i])
                if ia | ib == ic:continue
                elif ic == 0:
                    res += 1 if ia * ib == 0 else 2
                else:
                    res += 1
    
            return res
  • 相关阅读:
    JVM 垃圾收集与内存分配
    JVM 内存管理机制
    JVM 启动调优总结
    Visual Studio 2019 秘钥
    dubbo初学采坑记
    Intellij idea 一个窗口打开多模块并添加依赖
    Intellij idea 自动生成serialVersionUID
    office visio 2019 下载激活
    ASP.NET Core中的配置
    electron快捷键
  • 原文地址:https://www.cnblogs.com/seyjs/p/12204727.html
Copyright © 2011-2022 走看看