一道有趣的题:计算两个整数的和(不能使用加减法)——半加法

题目连接code

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

Example 1:leetcode

Input: a = 1, b = 2 Output: 3get

Example 2:io

Input: a = -2, b = 3 Output: 1class

思路: 采用半加法的思想, 即两个二进制数单独的位相加其结果能够用异或运算获得,进位能够用与运算获得。循环

例子2+3,至关于10+11二进制

1.10^11=01,carry=(10&11)<<1=100while

2.001^100=101,carry(001&100)<<1=0co

3.由于carry已经为0,不产生进位,此时的异或运算即为加法的结果101

递归版本

`
class Solution {

public int getSum(int a, int b) {

    if(b==0)return a;

    int carry=(a&b)<<1;

    int sum=a^b;

    return getSum(sum,carry);

}

}

`

循环版本

`
class Solution {

public int getSum(int a, int b) {

    while (b!=0){

        int carry=(a&b)<<1;

        a=a^b;

        b=carry;

    }

    return a;

}

}

`

相关文章
相关标签/搜索