(Leetcode)371. Sum of Two Integers

原创 2016年08月28日 21:27:47

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);
    }
}
版权声明:本文为博主原创文章,转载请附上原文链接。

相关文章推荐

Leetcode 371. Sum of Two Integers

371. Sum of Two Integers Total Accepted: 8805 Total Submissions: 17071 Difficulty: Easy Calc...

【题解】Leetcode.371. Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. ...

[LeetCode] 371. Sum of Two Integers

371. Sum of Two Integers(Easy) 常规解法,巧妙解法,内存机制?

leetcode371-----Sum of Two Integers

问题: Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -...

LeetCode 371.Sum of Two Integers 位运算实现加法(减法)

1.原题Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.(...

LeetCode笔记:371. Sum of Two Integers

不使用加号减号达到计算两个整数之和的目的

LeetCode#371. Sum of Two Integers(位运算)

位运算计算两个整数的和 位运算面试题

LeetCode之路:371. Sum of Two Integers

LeetCode之路:371. Sum of Two Integers 一、引言这道题非常小巧,题干非常简洁: Calculate the sum of two integers a and b,...

LeetCode 371: Sum of Two Integers 题解

原题如下:LeetCode 371: Sum of Two Integers Problem: Calculate the sum of two integers a and b, but y...

[leetcode]--371. Sum of Two Integers

Question 371: Calculate the sum of two integers a and b, but you are not allowed to use the operat...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)