【问题标题】:Adding a two number without using + sign [duplicate]在不使用 + 号的情况下添加两个数字 [重复]
【发布时间】:2013-10-01 09:36:11
【问题描述】:

我是 9 年级,我的数学老师让我在不使用 + 登录 C 程序的情况下添加数字。

我尝试了a - (-b) = a + b;,但我的数学老师想要其他选择。

【问题讨论】:

  • 你的解决方案是我最先想到的。
  • 他可能是指按位计算?在我的脑海中:AND 发现将携带的位,XOR 相加;然后将 AND 结果左移并重复将其添加到 XOR 值直到没有 AND 离开?
  • 也许可以尝试更多...迭代。 (想想while
  • 你真的应该问你的教授更具体的限制。下面基于对数的方法很优雅,但似乎有点太“简单”了。鉴于这是一门编程课程,我怀疑您的教授希望您使用基于布尔逻辑的方法,而不是代数方法。对以下所有解决方案 +1!
  • 虽然这个问题比较有趣,但这是要求他做功课。

标签: c


【解决方案1】:

在你的 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;
}

【讨论】:

    【解决方案2】:

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

    int add(int x, int y){
        return y == 0 ? x : add( x ^ y, (x & y) << 1);
    }
    

    P.S.:它是 vikas 提出的算法的递归版本。

    【讨论】:

      【解决方案3】:

      在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);
      
      }
      

      在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);
      }
      

      【讨论】:

        【解决方案4】:

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

        Temp= Anti Log(a)* Anti Log(b);
        
        a+b value is equals to log(Temp);
        

        适用于整数而不是双精度。

        【讨论】:

        • 有什么区别?
        • 我喜欢这个逻辑。它适用于整数。
        • 差异不完全相等。小数点后有一些差异
        • for ab = log(antilog(a)/antlog(b)) for a*b=log(antiLog(a)+antLog(b)) for a/b= log((antilog( a)-(antilog(b)))
        • “反对数”是一个非常奇怪的名字,考虑到对数本身被定义为取幂的倒数...
        【解决方案5】:
        #include<stdio.h>
        
        int add(int a, int b) {
            return (int)&((char *)a)[b];
        }
        
        int main() {
            printf("%d", add(5, 17));
            getchar();
        }
        

        不可移植,但不使用“+”字符。这会将 a 转换为 char 指针,用 [] 将 b 添加到它,然后将其转换回 int。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-12
          • 1970-01-01
          相关资源
          最近更新 更多