48 do not do addition subtraction multiplication and division

Title Description

A write function, and the sum of two integers, the function may not be used in vivo requires +, -, *, / four arithmetic symbols.

Ideas analysis

Direct thought-bit computing. & Bits corresponding to the calculated feed (1 & 1 = 1), corresponding to the calculated ^ adder (different from 1, with 0). When the carry is 1, the cycle continues (herein should carry left, this is understood to binary 1 *); When the carry is 0, is the final result.
eg. in decimal example. 5 + 7 => 2 is calculated for the bit, binary value 1 * 4 = + 10.5> calculated as 9 bits, the carry is 0.

Code

public static int Add(int num1, int num2) {
    int res = 0, carry = 0;
    do {
        res = num1 ^ num2;
        carry = (num1 & num2)<<1;
        num1 = res;
        num2 = carry;
    }while (carry != 0);
    return res;
}
Published 117 original articles · won praise 8 · views 3705

Guess you like

Origin blog.csdn.net/qq_34761012/article/details/104515369