
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Position of Rightmost Bit with First Carry in Sum of Two Binary in C++
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,
#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
Advertisements