- Related Questions & Answers
- Position of rightmost common bit in two numbers in C++
- Position of rightmost set bit in C++
- Position of rightmost different bit in C++
- 8085 program to sum of two 8 bit numbers without carry
- Golang Program to find the position of the rightmost set bit
- 8086 program to add two 16 bit BCD numbers with carry
- Find position of left most dis-similar bit for two numbers in C++
- 8086 program to add two 16-bit numbers with or without carry
- Find position of the only set bit in C++
- Print leftmost and rightmost nodes of a Binary Tree in C Program.
- Sum of sum of first n natural numbers in C++
- Addition of two numbers without propagating Carry?
- Python Program to Clear the Rightmost Set Bit of a Number
- Count even length binary sequences with same sum of first and second half bits in C++
- Minimum sum path between two leaves of a binary trees in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

Program to show the implementation of our solution,

#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

Advertisements