(Leetcode)371. Sum of Two Integers

来源:互联网 发布:java http文件服务器 编辑:程序博客网 时间:2024/04/29 02:59

371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.

Solution

思路

题目要求不用+法进行加法运算,所以考虑用&和^运算来代替。
“^” XOR operation, 获得(a+b)的“和”in each bit
“&” AND operation, 获得(a+b)的“进位”in each bit.
因为进位是进到下一位的,所以要把(a&b)<<1

递归调用一下下

Code

public class Solution {    public int getSum(int a, int b) {        if(b==0)            return a;        int sum = a^b;        int carrybit = (a&b)<<1;        return getSum(sum,carrybit);    }}
0 0
原创粉丝点击