劍指offer-不用加減乘除做加法

Topic describes

Topic describes

Nowcoder Link

Train of thought

When we have a problem where we are not allowed to use the four operations, our first thought must to do it with bitwise operations.

this question we need two operations, 1. xor(^) 2. and(&)

what's xor

Exclusive disjunction(also called exclusive or, XOR) essentially means either one, but not both nor none. In other words, the statement is true , If and only if one is true and the other is false.

0 ^ 0 -> 0
0 ^ 1 -> 1
1 ^ 0 -> 1
1 ^ 1 -> 0

what's and

If both values ??are all 1, the result is 1, otherwise it is 0

0 ^ 0 -> 0
0 ^ 1 -> 0
1 ^ 0 -> 0
1 ^ 1 -> 1

Let's show a example


example

Through this example, we know use xor(^) we can calculate the result but no carry, and use and(&) we can calculate the carry, so we have a solution, we can let number1 ^ number2 get the no carry result, and let number1 & number2 get the carry, and let the two result add(not real add, only repeat the above operation) until to number2 is 0(no carry)

Let's see the other example, we want to know 5 + 7 (we know the result is 12 (1100)):

1. we know 5 is 101, and 7 is 111
2. calculate 101 ^ 111 -> 010 (no carry result)
   calculate 101 & 111 << 1 -> 1010 (carry result)

 let no carry result add carry result (010 + 1010) (repeat the above action)

3. calculate 010 ^ 1010 -> 1000
   calculate 010 & 1010 << 1 = 100

 let no carry result add carry result (1000 + 100) (repeat the above action)

4. calculate 1000 ^ 100 = 1100
   calculate 1000 & 100 = 0

carry is 0, so 1100 is the last result

the result is 1100

so our code is :

public int Add(int num1, int num2) {
        while (num2 != 0) {
            int temp = num1 ^ num2;
            num2 = (num1 & num2) << 1;
            num1 = temp;
        }
        return num1;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容