• 【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
  • 相关阅读:
    自制DEV皮肤
    网格系统,菜单、按钮及导航
    表单
    排版
    Bootstrap的HTML标准模板
    ecshop常用的修改内容
    删除ECSHOP后台左侧导航菜单
    dede 内容页文章标题显示不全的更改方法
    dede 鼠标移到标题处显示完整标题
    Artlist标签去掉table
  • 原文地址:https://www.cnblogs.com/seyjs/p/12204727.html
Copyright © 2020-2023  润新知