不使用+运算符将两个数字相加的最佳方法是什么? [英] What is the best way to add two numbers without using the + operator?
本文介绍了不使用+运算符将两个数字相加的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我和一个朋友来回去与脑筋急转弯,我不知道如何解决这个问题。我的假设是可以使用某些按位运算符,但不确定。
A friend and I are going back and forth with brain-teasers and I have no idea how to solve this one. My assumption is that it's possible with some bitwise operators, but not sure.
推荐答案
在C中,按位运算符:
#include<stdio.h>
int add(int x, int y) {
int a, b;
do {
a = x & y;
b = x ^ y;
x = a << 1;
y = b;
} while (a);
return b;
}
int main( void ){
printf( "2 + 3 = %d", add(2,3));
return 0;
}
XOR( x ^ y
)是没有进位的加法。 (x& y)
是每个位的进位。 (x& y)<< 1
是每个位的进位。
XOR (x ^ y
) is addition without carry. (x & y)
is the carry-out from each bit. (x & y) << 1
is the carry-in to each bit.
循环不断添加进位,直到所有位的进位为零为止。
The loop keeps adding the carries until the carry is zero for all bits.
这篇关于不使用+运算符将两个数字相加的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文