用手将两个二进制数相加时,请牢记进位并将其同时相加。但是要在程序中执行相同的操作,我们需要进行大量检查。递归解可以想象为进位和a ^ b (两个输入)的加法,直到进位变为0为止。
例子 :
Input : int x = 45, y = 45
Output : 90
Input : int x = 4, y = 78
Output : 82
通过对两个位执行XOR(^),可以获得两个位的总和。进位可以通过对两个位进行“与”(&)获得。
上面是简单的Half Adder逻辑,可用于将2个单个位相加。我们可以将此逻辑扩展为整数。如果x和y在同一位置没有设置位,则x和y的按位XOR(^)得出x和y的总和。为了并入公共置位位,还使用了按位与(&)。 x和y的按位与运算得到所有进位。我们计算(x&y)<< 1并将其添加到x ^ y中以获得所需的结果。
一个重要的观察结果是,如果(x&y)变为0,则结果为x ^ y。
C
// C program to do recursive addition
// of two integers
#include
int add(int x, int y) {
int keep = (x & y) << 1;
int res = x^y;
// If bitwise & is 0, then there
// is not going to be any carry.
// Hence result of XOR is addition.
if (keep == 0)
return res;
add(keep, res);
}
// Driver code
int main(){
printf("%d", add(15, 38));
return 0;
}
Java
// Java program to do recursive addition
// of two integers
import java.io.*;
class GFG {
static int add(int x, int y)
{
int keep = (x & y) << 1;
int res = x^y;
// If bitwise & is 0, then there
// is not going to be any carry.
// Hence result of XOR is addition.
if (keep == 0)
return res;
return add(keep, res);
}
// Driver code
public static void main (String[] args)
{
System.out.println(add(15, 38));
}
}
// This code is contributed by Ajit.
Python3
# Python program to do recursive addition
# of two integers
def add(x, y):
keep = (x & y) << 1;
res = x^y;
# If bitwise & is 0, then there
# is not going to be any carry.
# Hence result of XOR is addition.
if (keep == 0):
return res;
return add(keep, res);
# Driver code
print(add(15, 38));
# This code is contributed by Princi Singh
C#
// C# program to do recursive
// addition of two integers
using System;
class GFG {
static int add(int x, int y)
{
int keep = (x & y) << 1;
int res = x^y;
// If bitwise & is 0, then there
// is not going to be any carry.
// Hence result of XOR is addition.
if (keep == 0)
return res;
return add(keep, res);
}
// Driver code
public static void Main ()
{
Console.Write(add(15, 38));
}
}
// This code is contributed by Smitha.
PHP
Javascript
输出:
53