📌  相关文章
📜  将数字转换为二进制表示形式,并且不带进位就将它们相加

📅  最后修改于: 2021-04-29 01:18:14             🧑  作者: Mango

给定两个数字NM。然后将两个数字转换为二进制形式的任务然后将两个二进制转换后的数字的相应位相加,但要在给定条件下,此加法中没有任何进位系统。

Input: N = 37, M = 12
Output: 41

Input: N = 456, M = 854
Output: 670

方法:

  • 如果我们不考虑进位,则两位的二进制加法将是:
    1 + 0 = 1
        0 + 1 = 1
        0 + 0 = 0
        1 + 1 = 0 (No carry)
    
  • 如果您观察清楚,您会发现这只是两个数字的按位XOR。

下面是上述方法的实现

C++
// C++ program to add two binary
// number without carry
#include
using namespace std;
  
// Function returns sum of both 
// the binary number without
// carry
int NoCarrySum(int N, int M)
{
    // XOR of N and M
    return N ^ M;
}
      
// Driver code
int main()
{
    int N = 37;
    int M = 12;
      
    cout << NoCarrySum(N, M);
    return 0;
}


Java
// Java program to add two binary
// number without carry
import java.util.*;
  
class GFG{
  
// Function returns sum of both 
// the binary number without
// carry
static int NoCarrySum(int N, int M)
{
    // XOR of N and M
    return N ^ M;
}
      
// Driver code
public 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 = 37
M = 12
print(NoCarrySum(N, M)) 
  
# This code is contributed by sayesha


C#
// C# program to add two binary
// number without carry
using System;
  
class GFG{
  
// Function returns sum of both 
// the binary number without
// carry
static int NoCarrySum(int N, int M)
{
      
    // XOR of N and M
    return N ^ M;
}
      
// Driver code
static public void Main(String[] args)
{
    int N = 37;
    int M = 12;
    Console.Write(NoCarrySum(N, M));
}
}
  
// This code is contributed by Rajput-Ji


输出:
41