A+B的问题(使用位运算)

Clarification

Are a and b both 32-bit integers?

  • Yes.

Can I use bit operation?

  • Sure you can.

Example

Given a=1 and b=2 return 3.

Challenge

Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use + or any arithmetic operators.)


java解决方法:

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) {
        if(b == 0)
            return a;
        int numa = a^b;
        int numb = (a&b)<<1;
        return aplusb(numa,numb);
    }
}

关于位运算:(java中)

<< 位元向左移动后,最高位的位元会消失,最低位的位元补0;

>> 位元向右移动后,最低位的位元会消失,最高位的位元补0.

<< SHIFT LEFT
>> SHIFT RIGHT

這兩個運算子的功能主要是移動一個變數中的所有位元,位元向左 / 向右移動之後,最高位 / 最低位的位元會消失,最低位 / 最高位的位元補 0 

5 << 1 = 10	// 00101 的全部位元向左移動一位數變成 01010。
    5 << 2 = 20     // 00101 的全部位元向左移動兩位數變成 10100。
    5 >> 1 = 2	    // 00101 的全部位元向右移動一位數變成 00010。
    5 >> 2 = 1	    // 00101 的全部位元向右移動一位數變成 00001。

你可能感兴趣的:(A+B的问题(使用位运算))