(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 位运算实现加法(减法)

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...
  • Artprog
  • Artprog
  • 2016年08月17日 11:48
  • 422

[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...

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

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 -. ...

371.Sum of Two Integers

给你两个数,a和b,求这两个整数的和。但是在程序中不能使用" + "和" - "号 例如:给你a =1, b = 2 返回 3 对于这个问题,想吐槽的很多: 1.python弱类型的缺点...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:(Leetcode)371. Sum of Two Integers
举报原因:
原因补充:

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