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

2023-11-13

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

题解:

class Solution {
public:
    int minFlips(int a, int b, int c) {
        int res = 0;
        for (int i = 0; i < 32; i++) {
            int k1 = a & (1 << i);
            int k2 = b & (1 << i);
            int k3 = c & (1 << i);
            if (k3 == 0) {
                if (k1 != k3) {
                    res++;
                }
                if (k2 != k3) {
                    res++;
                }
            }
            else {
                if (k1 != k3 && k2 != k3) {
                    res++;
                }
            }
        }
        return res;
    }
};

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

LeetCode-1318. Minimum Flips to Make a OR b Equal to c 的相关文章

  • 物理服务器和云服务器的区别

    1 从概念上区分 云服务器 云主机 是在一组集群服务器商虚拟出多个类似独立服务器的部分 集群中每个服务器上都有该云服务器的一个镜像 形象地讲 集群服务器犹如一个大型的公共停车场 而云服务器的使用 则是卖给了你停车的权利 独立服务器 顾名思义
  • 如何做数据清洗?

    一 预处理阶段 预处理阶段主要做两件事情 一是将数据导入处理工具 通常来说 建议使用数据库 单机跑数搭建MySQL环境即可 如果数据量大 千万级以上 可以使用文本文件存储 python操作的方式 而是看数据 这里包含两个部分 一是看元数据
  • 第四章 索引和视图 总结

    第四章 索引和视图 1 索引 索引主要分为聚类索引和非聚类索引 聚类索引 表中数据行的物理存储顺序与索引顺序完全相同 每个表只能有一个聚类索引 物理的重拍表中的数据以符合索引约束 用于经常查找的列 非聚类索引 不改变表中数据行的物理存储位置

随机推荐