对于一个数的每个置位的比特,切换 C++ 的另一个比特


在这个问题中,我们拿到了两个整数。我们的任务是创建一个 c 程序来进行操作,对于一个数的每个置位的比特,切换另一个比特。

下面,我们通过一个例子来理解这个问题。

Input: 3 7
Output: 4
Binary of 3: 011
Binary of 3: 111

数字的第一个和第二个比特被翻转,它变为 100,即 4。

解决方法

解决该问题的办法是执行两个数的异或操作。无论何时第一个比特为 1,结果的相应比特都将使用异或运算切换。

示例

一个程序来说明我们解决方案的工作原理

Open Compiler
#include <bits/stdc++.h> using namespace std; int main(){ int a = 3, b = 7; cout<<"The numbers are "<<a<<" & "<<b<<endl; cout<<"The result of flipping bits is "<<(a ^ b); return 0; }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

The numbers are 3 & 7
The result of flipping bits is 4

更新于: 2022 年 2 月 1 日

226 次浏览

职业启动

通过完成课程获得认证

开始学习
广告