Position of rightmost bit with first carry in sum of two binary in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two positive integers N and M. Our task is to print the rightmost bit that generates the first carry bit in the binary addition of the sum of N and M.

Let’s take an example to understand the problem,

Input − N = 5, M = 14

Output − 3

Explanation

(5)2 = 0101 , (14)2 = 1110
Sum 0101
+   1110
10011

To solve this problem, we will consider some observations from boolean algebra.

The sum will generate a carry when both numbers are 1. So, we will find all bits where carry is generated. This will be done by finding the and operation of both the numbers. And the find the rightmost bit of the number.

This seems a bit complex to understand let’s solve an example using this method.

N = 5 and M = 14
N&M = 0100

A rightmost set bit here is at index 3.

Example

Program to show the implementation of our solution,

Live Demo

#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;
}

Output

The position of rightmost bit that generates carry in the sum of 4 and 14 is 3
Published on 17-Apr-2020 08:09:48