【问题标题】:How to add two variables without using a '+' operator? [duplicate]如何在不使用“+”运算符的情况下添加两个变量? [复制]
【发布时间】:2016-10-14 11:14:58
【问题描述】:

我在一次采访中被问到这个问题:

如何在不使用“+”运算符的情况下添加两个变量?

面试官问我,我答不上来,虽然我是一个优秀的 C 程序员!

【问题讨论】:

  • 也许x - (- y) ?
  • @coredump 做了同样的事情,但他坚持我不要那样做!!
  • @2501 但算法没有改变
  • @Anjaneyulu 不幸的是,这个职位要求你能够进行读心术。
  • @Matt 这是未定义的行为,因为它对在多个子表达式上读取的变量有未排序的副作用。或者简而言之:你的表达是错误的和非法的。

标签: c


【解决方案1】:

使用 bitwise 运算符,您可以将两个数字相加。试试下面:

   int Sum(int a, int b)
    {
        // Iterate till there is no carry  
        while (b != 0)
        {
            // now carry 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;
    }

使用 递增和递减 运算符,您可以添加两个数字。 另一种方式可能是:

int Sum(int a, int b)
{
    // Iterate till there b becomes zero
    while (b--)
    {
        a++;
    }
    return a;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2019-04-22
    相关资源
    最近更新 更多