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 <= 10^9
  • 1 <= b <= 10^9
  • 1 <= c <= 10^9

From: LeetCode

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


Solution:

Ideas:

For each bit position:

  • When the corresponding bit of c is 0, both bits in a and b must be 0.
    • Add one flip for every bit that is currently 1.
  • When the corresponding bit of c is 1, at least one of the bits in a or b must be 1.
    • If both are 0, one flip is required.
Code:
c 复制代码
int minFlips(int a, int b, int c) {
    int flips = 0;

    while (a != 0 || b != 0 || c != 0) {
        int bitA = a & 1;
        int bitB = b & 1;
        int bitC = c & 1;

        if (bitC == 0) {
            // Both bits must be 0.
            flips += bitA + bitB;
        } else {
            // At least one bit must be 1.
            if (bitA == 0 && bitB == 0) {
                flips++;
            }
        }

        a >>= 1;
        b >>= 1;
        c >>= 1;
    }

    return flips;
}
相关推荐
电科_银尘1 小时前
【大模型算法与工程 39】PPO:策略比率、裁剪目标与训练稳定性
人工智能·算法·机器学习
shehuiyuelaiyuehao2 小时前
算法68,字符串相乘
算法
Huangjin007_2 小时前
【C++ 算法竞赛篇】STL 常用知识点速通指南
c++·算法
驭渊的小故事4 小时前
LeetCode 33:搜索旋转排序数组——从二分查找到旋转数组的区间判定
算法·leetcode·职场和发展
炸膛坦客4 小时前
单片机/C/C++八股:(三十三)取别名
c语言·c++·单片机
听情歌落俗5 小时前
嵌入式学习1-C语言基础语法与STM32实践
c语言·开发语言
小飞在努力5 小时前
【实现负载均匀在线判题⑤】MVC 架构搭建与 Model 题目数据模块实现
c语言·开发语言·c++·笔记·后端
htzyl2065 小时前
金额计算:为什么前端不该用浮点数存钱
前端·javascript·算法
电科_银尘6 小时前
【大模型算法与工程 32】全量微调与参数高效微调:如何选择
人工智能·算法·机器学习