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++
// C++ program to add two binary// number without carry#include<bits/stdc++.h>using namespace std;// Function returns sum of both // the binary number without// carryint NoCarrySum(int N, int M){ // XOR of N and M return N ^ M;} // Driver codeint main(){ int N = 37; int M = 12; cout << NoCarrySum(N, M); return 0;} |
Java
// Java program to add two binary// number without carryimport java.util.*;class GFG{// Function returns sum of both // the binary number without// carrystatic int NoCarrySum(int N, int M){ // XOR of N and M return N ^ M;} // Driver codepublic static void main(String[] args){ int N = 37; int M = 12; System.out.print(NoCarrySum(N, M));}}// This code is contributed by amal kumar choubey |
Python3
# Python3 program to add two binary # number without carry # Function returns sum of both # the binary number without # carry def NoCarrySum(N, M): # XOR of N and M return N ^ M# Driver code N = 37M = 12print(NoCarrySum(N, M)) # This code is contributed by sayesha |
C#
// C# program to add two binary// number without carryusing System;class GFG{// Function returns sum of both // the binary number without// carrystatic int NoCarrySum(int N, int M){ // XOR of N and M return N ^ M;} // Driver codestatic public void Main(String[] args){ int N = 37; int M = 12; Console.Write(NoCarrySum(N, M));}}// This code is contributed by Rajput-Ji |
Javascript
<script>// Javascript program to add two binary// number without carry// Function returns sum of both // the binary number without// carryfunction NoCarrySum(N, M){ // XOR of N and M return N ^ M;} // Driver code let N = 37; let M = 12; document.write(NoCarrySum(N, M));</script> |
41
Time complexity : O(1)
Auxiliary space : O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
