不使用+号添加两个数字

8 c

我9年级,我的数学老师让我+在C程序中使用登录添加数字.

我试过, a - (-b) = a + b;但我的数学老师想要一些其他的选择.

Vik*_*ana 22

在c程序中使用此功能

int Add(int a, int b)
{
    while (b)
    {
        // carry now contains common set bits of "a" and "b"
        int carry = a & b;

        // Sum of bits of "a" and "b" where at least one of the bits is not set
        a = a ^ b;

        // Carry is shifted by one so that adding it to "a" gives the required sum
        b = carry << 1;
    }
    return a;
}
Run Code Online (Sandbox Code Playgroud)


zav*_*avg 11

使用按位^&运算符和递归

int add(int x, int y){
    return y == 0 ? x : add( x ^ y, (x & y) << 1);
}
Run Code Online (Sandbox Code Playgroud)

PS:它是vikas提出的算法的递归版本.


Sar*_*rma 7

使用Anti Log()你可以做到这一点

Temp= Anti Log(a)* Anti Log(b);

a+b value is equals to log(Temp);
Run Code Online (Sandbox Code Playgroud)

适用于不是双精度的整数.

  • "Anti Log"是一个非常奇怪的名字,考虑到对数_is本身定义为取幂的倒数... (5认同)
  • 有什么不同? (3认同)

Saj*_*tta 7

在Java中使用递归 -

public static int add(int a, int b){

    if(b == 0) return a;
    int sum = a ^ b;
    int carry = (a & b) << 1;

    return add(sum, carry);

}
Run Code Online (Sandbox Code Playgroud)

在C-

int add(int a, int b){

    if(b == 0) return a;
    int sum = a ^ b;
    int carry = (a & b) << 1;

    return add(sum, carry);
}
Run Code Online (Sandbox Code Playgroud)