两个二进制数之和中最右侧位产生第一个进位位的坐标
在本问题中,给出两个正整数 N 和 M。我们的任务是打印出二进制中 N 和 M 求和时生成第一个进位位的最右侧位。
举个例子来理解问题,
输入 − N = 5,M = 14
输出 − 3
说明 −
(5)2 = 0101 , (14)2 = 1110 Sum 0101 + 1110 10011
要解决这个问题,我们来考虑一下布尔代数的一些观察。
当两个数字都是 1 时,求和将会产生进位。所以,我们要找出所有产生进位的位。这可以通过查找两个数字的与运算来完成。并且找到该数字的最右侧位。
这看起来有点难以理解,让我们用这种方法解决一个例子。
N = 5 and M = 14 N&M = 0100
这里最右侧的设置位在索引 3 处。
示例
程序展示了我们解决方案的实现,
#include <iostream>
#include <math.h>
using namespace std;
int rightSetBit(int N) {
int bitIndex = log2(N & -N)+1;
return bitIndex;
}
void rightCarryBit(int N, int M) {
int carryIndex = rightSetBit(N & M);
cout<<carryIndex;
}
int main() {
int N=4, M=14;
cout<<"The position of rightmost bit that generates carry in the sum of "<<N<<" and "<<M<<" is ";
rightCarryBit(N,M);
return 0;
}输出
The position of rightmost bit that generates carry in the sum of 4 and 14 is 3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP