题
有一个朋友和我要来回脑筋急转弯,我不知道如何解决这一个。我的假设是,它可能与某些位运算符,但不能肯定。
解决方案
在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
是搬入于每个位
在环保持添加携带,直到提的是对于所有位零。
其他提示
int add(int a, int b) {
const char *c=0;
return &(&c[a])[b];
}
没有+右?
int add(int a, int b)
{
return -(-a) - (-b);
}
CMS的add()函数是美丽的。它不应该被一元否定(:-y ==(〜y)的1的非位运算,相当于使用加法)来玷污。因此,这里是使用相同的仅按位设计减法功能:
int sub(int x, int y) {
unsigned a, b;
do {
a = ~x & y;
b = x ^ y;
x = b;
y = a << 1;
} while (a);
return b;
}
定义 “最好”。这里的一个Python版本:
len(range(x)+range(y))
在+
执行列表连接,而不是加法。
Java解决方案与位运算符:
// Recursive solution
public static int addR(int x, int y) {
if (y == 0) return x;
int sum = x ^ y; //SUM of two integer is X XOR Y
int carry = (x & y) << 1; //CARRY of two integer is X AND Y
return addR(sum, carry);
}
//Iterative solution
public static int addI(int x, int y) {
while (y != 0) {
int carry = (x & y); //CARRY is AND of two bits
x = x ^ y; //SUM of two bits is X XOR Y
y = carry << 1; //shifts carry to 1 bit to calculate sum
}
return x;
}
请注意,这将是被称为波进位加法器加法器,其工作原理,但并不表现最佳。内置硬件大多数二进制加法器是快速加法器的形式,如随身看超前加法器
如果carry_in设置为1,我还添加了标志,以显示对加溢或溢出我的波进位加法器同时适用于无符号和2的,如果你设置carry_in 0互补整数,1的补整数。
#define BIT_LEN 32
#define ADD_OK 0
#define ADD_UNDERFLOW 1
#define ADD_OVERFLOW 2
int ripple_add(int a, int b, char carry_in, char* flags) {
int result = 0;
int current_bit_position = 0;
char a_bit = 0, b_bit = 0, result_bit = 0;
while ((a || b) && current_bit_position < BIT_LEN) {
a_bit = a & 1;
b_bit = b & 1;
result_bit = (a_bit ^ b_bit ^ carry_in);
result |= result_bit << current_bit_position++;
carry_in = (a_bit & b_bit) | (a_bit & carry_in) | (b_bit & carry_in);
a >>= 1;
b >>= 1;
}
if (current_bit_position < BIT_LEN) {
*flags = ADD_OK;
}
else if (a_bit & b_bit & ~result_bit) {
*flags = ADD_UNDERFLOW;
}
else if (~a_bit & ~b_bit & result_bit) {
*flags = ADD_OVERFLOW;
}
else {
*flags = ADD_OK;
}
return result;
}
为什么不只是incremet所述第一数目为常,作为第二数?
原因ADD被汇编implememted作为单个指令,而不是作为位操作的一些组合是,它是很难做到的。你必须担心从给定的最低位到下一个更高序位进行。这是东西,机器在硬件做快,但即使有C,你不能用软件做快。
添加两个整数并不难;有二进制加法的例子很多在线
一个更具挑战性的问题是浮点数!有在 HTTP的例子://pages.cs .wisc.edu /〜smoler / x86text / lect.notes / arith.flpt.html
在使用Python位运算符:
def sum_no_arithmetic_operators(x,y):
while True:
carry = x & y
x = x ^ y
y = carry << 1
if y == 0:
break
return x
正在研究这个问题我在C#中,不能让所有的测试用例通过。然后我跨越此。
下面是在一个实施C#6:
public int Sum(int a, int b) => b != 0 ? Sum(a ^ b, (a & b) << 1) : a;
实施了同样的方式,我们可以做在纸上二进制加法。
int add(int x, int y)
{
int t1_set, t2_set;
int carry = 0;
int result = 0;
int mask = 0x1;
while (mask != 0) {
t1_set = x & mask;
t2_set = y & mask;
if (carry) {
if (!t1_set && !t2_set) {
carry = 0;
result |= mask;
} else if (t1_set && t2_set) {
result |= mask;
}
} else {
if ((t1_set && !t2_set) || (!t1_set && t2_set)) {
result |= mask;
} else if (t1_set && t2_set) {
carry = 1;
}
}
mask <<= 1;
}
return (result);
}
改进的速度将低于::
int add_better (int x, int y)
{
int b1_set, b2_set;
int mask = 0x1;
int result = 0;
int carry = 0;
while (mask != 0) {
b1_set = x & mask ? 1 : 0;
b2_set = y & mask ? 1 : 0;
if ( (b1_set ^ b2_set) ^ carry)
result |= mask;
carry = (b1_set & b2_set) | (b1_set & carry) | (b2_set & carry);
mask <<= 1;
}
return (result);
}
我认为这是在编码面试中的问题18.1。 我的Python溶液:
def foo(a, b):
"""iterate through a and b, count iteration via a list, check len"""
x = []
for i in range(a):
x.append(a)
for i in range(b):
x.append(b)
print len(x)
此方法使用迭代,所以时间复杂度不是最佳的。 我认为最好的办法是在为位操作水平较低的工作。
这是我对Python实现。它工作得很好,当我们知道字节(或比特)的数量。
def summ(a, b):
#for 4 bytes(or 4*8 bits)
max_num = 0xFFFFFFFF
while a != 0:
a, b = ((a & b) << 1), (a ^ b)
if a > max_num:
b = (b&max_num)
break
return b
可以使用比特移位和AND运算做到这一点。
#include <stdio.h>
int main()
{
unsigned int x = 3, y = 1, sum, carry;
sum = x ^ y; // Ex - OR x and y
carry = x & y; // AND x and y
while (carry != 0) {
carry = carry << 1; // left shift the carry
x = sum; // initialize x as sum
y = carry; // initialize y as carry
sum = x ^ y; // sum is calculated
carry = x & y; /* carry is calculated, the loop condition is
evaluated and the process is repeated until
carry is equal to 0.
*/
}
printf("%d\n", sum); // the program will print 4
return 0;
}
如果输入是相反的符号的最投答案将不起作用。然而,以下将。我曾在一个地方被骗了,但只保持代码有点干净。改进欢迎任何建议
def add(x, y):
if (x >= 0 and y >= 0) or (x < 0 and y < 0):
return _add(x, y)
else:
return __add(x, y)
def _add(x, y):
if y == 0:
return x
else:
return _add((x ^ y), ((x & y) << 1))
def __add(x, y):
if x < 0 < y:
x = _add(~x, 1)
if x > y:
diff = -sub(x, y)
else:
diff = sub(y, x)
return diff
elif y < 0 < x:
y = _add(~y, 1)
if y > x:
diff = -sub(y, x)
else:
diff = sub(y, x)
return diff
else:
raise ValueError("Invalid Input")
def sub(x, y):
if y > x:
raise ValueError('y must be less than x')
while y > 0:
b = ~x & y
x ^= y
y = b << 1
return x
下面是一个便携式单行三元和递归溶液。
int add(int x, int y) {
return y == 0 ? x : add(x ^ y, (x & y) << 1);
}
的Python代码: (1)
add = lambda a,b : -(-a)-(-b)
与使用lambda函数 ' - ' 运算符
(2)
add= lambda a,b : len(list(map(lambda x:x,(i for i in range(-a,b)))))