ACWING85. Do not do addition and subtraction, multiplication and division (to prove safety offer)

A write function, and the sum of two integers, the function may not be used in vivo requires +, -, ×, ÷ four operational sign.

Sample
input: num1 = 1, num2 = 2

Output: 3

Ideas:
very clever a question. Not by calculating an exclusive OR operation result into the adder, and then & calculation, then a right, whether calculated every need carry.

class Solution {
public:
    typedef long long ll;
    int add(int num1, int num2){
        while(num2) {
            int sum = (num1 ^ num2);
            int carry = (num1 & num2) << 1;
            num1 = sum;
            num2 = carry;
        }
        return num1;
    }
};
Published 844 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/tomjobs/article/details/104976164