1. A + B Problem

1. A + B Problem

Description

Write a function that add two numbers A and B. You should not use + or any arithmetic operators.

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

Solution

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
        if(a==0 || b==0){
            return a==0?b:a;
        }
        int c = a^b;
        int d = (a&b)<<1;
        return aplusb(c,d);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章