sherine的博客

取法乎上,仅得乎中

(Leetcode)371. Sum of Two Integers

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);
    }
}
阅读更多
版权声明:本文为博主原创文章,转载请附上原文链接。 https://blog.csdn.net/muyu709287760/article/details/52347950
文章标签: leetcode
个人分类: Leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭