What is the best way to add two numbers without using the + operator?

后端 未结 22 1498
情书的邮戳
情书的邮戳 2020-11-27 05:18

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 n

相关标签:
22条回答
  • 2020-11-27 05:24

    I saw this as problem 18.1 in the coding interview. My python solution:

    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)
    

    This method uses iteration, so the time complexity isn't optimal. I believe the best way is to work at a lower level with bitwise operations.

    0 讨论(0)
  • 2020-11-27 05:27

    CMS's add() function is beautiful. It should not be sullied by unary negation (a non-bitwise operation, tantamount to using addition: -y==(~y)+1). So here's a subtraction function using the same bitwise-only design:

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 05:32

    No + right?

    int add(int a, int b) 
    {
       return -(-a) - (-b);
    }
    
    0 讨论(0)
  • 2020-11-27 05:32

    The most voted answer will not work if the inputs are of opposite sign. The following however will. I have cheated at one place, but only to keep the code a bit clean. Any suggestions for improvement welcome

    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
    
    0 讨论(0)
  • 2020-11-27 05:33

    In C, with bitwise operators:

    #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) 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.

    0 讨论(0)
  • 2020-11-27 05:34

    Go based solution

    func add(a int, b int) int {
    
    for {
        carry := (a & b) << 1
        a = a ^ b
        b = carry 
        if b == 0 {
            break
        }
    }
    
    return a 
    
    }
    

    same solution can be implemented in Python as follows, but there is some problem about number represent in Python, Python has more than 32 bits for integers. so we will use a mask to obtain the last 32 bits.

    Eg: if we don't use mask we won't get the result for numbers (-1,1)

    def add(a,b):   
        mask = 0xffffffff
    
        while b & mask:
            carry = a & b
            a = a ^ b
            b = carry << 1
    
        return (a & mask)
    
    0 讨论(0)
提交回复
热议问题