c++ - 如何在不使用++ 或 + 或其他算术运算符的情况下将两个数字相加

标签 c++ c algorithm bit-manipulation

如何在不使用++ 或 + 或任何其他算术运算符的情况下将两个数字相加?

这是很久以前在一些校园采访中提出的问题。不管怎样,今天有人问了一个关于一些位操作的问题,并回答了一个漂亮的 quide Stanford bit twiddling 被提及。我花了一些时间研究它,并认为这个问题实际上可能有答案。我不知道,我找不到一个。有答案吗?

最佳答案

这是我前段时间为了好玩而写的东西。它使用 two's complement表示并使用带有进位位的重复移位来实现加法,主要是在加法方面实现其他运算符。

#include <stdlib.h> /* atoi() */
#include <stdio.h>  /* (f)printf */
#include <assert.h> /* assert() */

int add(int x, int y) {
    int carry = 0;
    int result = 0;
    int i;

    for(i = 0; i < 32; ++i) {
        int a = (x >> i) & 1;
        int b = (y >> i) & 1;
        result |= ((a ^ b) ^ carry) << i;
        carry = (a & b) | (b & carry) | (carry & a);
    }

    return result;
}

int negate(int x) {
    return add(~x, 1);
}

int subtract(int x, int y) {
    return add(x, negate(y));
}

int is_even(int n) {
    return !(n & 1);
}

int divide_by_two(int n) {
    return n >> 1;
}

int multiply_by_two(int n) {
    return n << 1;
}

int multiply(int x, int y) {
    int result = 0;

    if(x < 0 && y < 0) {
        return multiply(negate(x), negate(y));
    }

    if(x >= 0 && y < 0) {
        return multiply(y, x);
    }

    while(y > 0) {
        if(is_even(y)) {
            x = multiply_by_two(x);
            y = divide_by_two(y);
        } else {
            result = add(result, x);
            y = add(y, -1);
        }
    }

    return result;
}

int main(int argc, char **argv) {
    int from = -100, to = 100;
    int i, j;

    for(i = from; i <= to; ++i) {
        assert(0 - i == negate(i));
        assert(((i % 2) == 0) == is_even(i));
        assert(i * 2 == multiply_by_two(i));
        if(is_even(i)) {
            assert(i / 2 == divide_by_two(i));
        }
    }

    for(i = from; i <= to; ++i) {
        for(j = from; j <= to; ++j) {
            assert(i + j == add(i, j));
            assert(i - j == subtract(i, j));
            assert(i * j == multiply(i, j));
        }
    }

    return 0;
}

关于c++ - 如何在不使用++ 或 + 或其他算术运算符的情况下将两个数字相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1149929/

相关文章:

c++ - 将数据存储在指针的最高有效位中

c++ - 堆解决方案优于堆栈?

arrays - 和为 k 的子矩阵数

c++ - 无情的 GCC C++ 编译器

c - 为什么下面的语句打印三次?

c++ - C++ Map中如何使用自定义结构

algorithm - 计算 L 和 R 之间至少有一个介于 1 到 50 之间的质因数的数

python - 从子集集中创建新的子集集(python)

c++ - Codecvt 在 gcc 中不起作用

c++ - 使用 Flex 和 Bison 在脚本引擎中实现 eval 和 load 函数