• LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c


    1318. Minimum Flips to Make a OR b Equal to c

    Given 3 positives numbers a, b 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 < = 1 0 9 1 <= a <= 10^9 1<=a<=109
    • 1 < = b < = 1 0 9 1 <= b <= 10^9 1<=b<=109
    • 1 < = c < = 1 0 9 1 <= c <= 10^9 1<=c<=109

    From: LeetCode
    Link: 1318. Minimum Flips to Make a OR b Equal to c


    Solution:

    Ideas:

    This function works by checking each bit position from the least significant bit to the most significant bit, calculating whether a flip is needed at each position, and then shifting the numbers to the right to check the next position. The count of flips is increased based on the bits of a, b, and c.

    Caode:
    int minFlips(int a, int b, int c) {
        int flips = 0;
        // Loop through each bit position until a, b, and c are all zero.
        while (a > 0 || b > 0 || c > 0) {
            // Check the rightmost bits of a, b, and c.
            int bit_a = a & 1;
            int bit_b = b & 1;
            int bit_c = c & 1;
    
            if ((bit_a | bit_b) != bit_c) {
                // If a OR b is not equal to c at this bit, we need to flip.
                if (bit_c == 0) {
                    // If c is 0, both a and b must be 0, so flip both if they are not.
                    flips += bit_a + bit_b;
                } else {
                    // If c is 1, at least one of a or b must be flipped to 1.
                    flips += 1;
                }
            }
    
            // Shift a, b, and c to the right by one to check the next bit.
            a >>= 1;
            b >>= 1;
            c >>= 1;
        }
        return flips;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
  • 相关阅读:
    【C++学习】基础1
    学习笔记——单调队列与单调栈
    MQ - 24 Pulsar集群架构设计与实现
    金融生产存储亚健康治理:升级亚健康 3.0 ,应对万盘规模的挑战
    WPF TextBox长文本模式
    光导布局设计工具
    MVC模式认识
    Flink 监控指南 被动拉取 Rest API
    阿里云国际版云服务器Linux和Windows操作系统的链路测试工具-Unirech
    LeetCode75——Day8
  • 原文地址:https://blog.csdn.net/navicheung/article/details/136138750