Position of rightmost bit with first carry in sum of two binary
Last Updated :
15 Jun, 2022
Given two non-negative integers a and b. The problem is to find the position of the rightmost bit where a carry is generated in the binary addition of a and b.
Examples:
Input : a = 10, b = 2
Output : 2
(10)10 = (1010)2
(2)10 = (10)2.
1010
+ 10
As highlighted, 1st carry bit from the right
will be generated at position '2'.
Input : a = 10, b = 5
Output : 0
'0' as no carry bit will be generated.
Approach: Following are the steps:
- Calculate num = a & b.
- Find the position of rightmost set bit in num.
C++
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
unsigned int posOfRightmostSetBit(ull n)
{
return log2(n & -n) + 1;
}
unsigned int posOfCarryBit(ull a, ull b)
{
return posOfRightmostSetBit(a & b);
}
int main()
{
ull a = 10, b = 2;
cout << posOfCarryBit(a, b);
return 0;
}
|
Java
class GFG {
static int posOfRightmostSetBit( int n)
{
return ( int )(Math.log(n & -n) / Math.log( 2 )) + 1 ;
}
static int posOfCarryBit( int a, int b)
{
return posOfRightmostSetBit(a & b);
}
public static void main(String[] args)
{
int a = 10 , b = 2 ;
System.out.print(posOfCarryBit(a, b));
}
}
|
Python3
import math
def posOfRightmostSetBit( n ):
return int (math.log2(n & - n) + 1 )
def posOfCarryBit( a , b ):
return posOfRightmostSetBit(a & b)
a = 10
b = 2
print (posOfCarryBit(a, b))
|
C#
using System;
class GFG {
static int posOfRightmostSetBit( int n)
{
return ( int )(Math.Log(n & -n) / Math.Log(2)) + 1;
}
static int posOfCarryBit( int a, int b)
{
return posOfRightmostSetBit(a & b);
}
public static void Main()
{
int a = 10, b = 2;
Console.Write(posOfCarryBit(a, b));
}
}
|
Javascript
<script>
function posOfRightmostSetBit(n)
{
return parseInt(Math.log(n & -n) /
Math.log(2)) + 1;
}
function posOfCarryBit(a, b)
{
return posOfRightmostSetBit(a & b);
}
var a = 10, b = 2;
document.write(posOfCarryBit(a, b));
</script>
|
Output:
2
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...