算法:位运算代替加法

public class Solution {
    /**
     * @param a: An integer
     * @param b: An integer
     * @return: The sum of a and b 
     */
    public int aplusb(int a, int b) {
        // write your code here
        int res=0;
		int xor=a^b;
		int forworad=(a&b)<<1;
        return forworad==0 ? xor : aplusb(xor,forworad);
    }
}

1、由a^b可得按位相加后没有进位的和及原位和;10^10=0

2、由a&b可得可以产生进位的地方;由(a&b)<<1得到进位后的值即进位和。(10&10)<<1=100

3、如何进位不为0,则使a=原位和,b=进位和,重复上述步骤。a和b分别为(0,100)

     原位和:0^100=100                进位和: (0&100)<<1=0

    如何进位为0,则相加的结果为原位和;如:(0&100)<<1=0   结果为:100    4

 

原文:https://blog.csdn.net/qq_38002337/article/details/79510341 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章