Convert numbers into binary representation and add them without carry
Last Updated :
01 Nov, 2023
Given two numbers N and M. The task to convert both the numbers in the binary form then add respective bits of both the binary converted numbers but with a given condition that there is not any carry system in this addition.
Input: N = 37, M = 12
Output: 41
Input: N = 456, M = 854
Output: 670
Approach:
- If we don’t consider carry then the binary addition of two bits will be:
1 + 0 = 1
0 + 1 = 1
0 + 0 = 0
1 + 1 = 0 (No carry)
- If you observe clearly you will notice that this is just bitwise XOR of two numbers.
Below is the implementation of the above approach
C++
#include<bits/stdc++.h>
using namespace std;
int NoCarrySum( int N, int M)
{
return N ^ M;
}
int main()
{
int N = 37;
int M = 12;
cout << NoCarrySum(N, M);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int NoCarrySum( int N, int M)
{
return N ^ M;
}
public static void main(String[] args)
{
int N = 37 ;
int M = 12 ;
System.out.print(NoCarrySum(N, M));
}
}
|
Python3
def NoCarrySum(N, M):
return N ^ M
N = 37
M = 12
print (NoCarrySum(N, M))
|
C#
using System;
class GFG{
static int NoCarrySum( int N, int M)
{
return N ^ M;
}
static public void Main(String[] args)
{
int N = 37;
int M = 12;
Console.Write(NoCarrySum(N, M));
}
}
|
Javascript
<script>
function NoCarrySum(N, M)
{
return N ^ M;
}
let N = 37;
let M = 12;
document.write(NoCarrySum(N, M));
</script>
|
Time complexity : O(1)
Auxiliary space : O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...