美文网首页
lint0001 A + B Problem

lint0001 A + B Problem

作者: 日光降临 | 来源:发表于2019-02-04 21:39 被阅读0次

Write a function that add two numbers A and B.

Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use + or any arithmetic operators.)

public class Solution {
    public int aplusb(int a, int b) {
        // 异或运算有一个别名叫做:不进位加法
        // 那么a ^ b就是a和b相加之后,该进位的地方不进位的结果
        // 然后下面考虑哪些地方要进位,自然是a和b里都是1的地方
        // a & b就是a和b里都是1的那些位置,a & b << 1 就是进位
        // 之后的结果。所以:a + b = (a ^ b) + (a & b << 1)
        // 令sum = a ^ b, carry = (a & b) << 1
        // 可以知道,这个过程是在模拟加法的运算过程,进位不可能
        // 一直持续,所以carry最终会变为0。因此重复做上述操作就可以
        // 求得a + b的值。
         while(b!=0){
           int sum = a^b;
           int carry = (a&b)<<1;
           a = sum;
           b = carry;
        }
        return a;
    }
}

假设a=3, that is 0011, b=5, that is 0101,
a^b=0110, a&b<<1 = 0010, 他们两个再相加,重复这个过程,直到b,也就是进位为0

  • python的解答,未知正确与否
class Solution:
def aplusb(self, a, b):
# write your code here
if a == b: return a <<1
if a == -b: return 0
while(b != 0):
tmpA = a^b
b = (a&b)<<1
a = tmpA
return a

相关文章

  • lint0001 A + B Problem

    Write a function that add two numbers A and B. Of course ...

  • lint0001 A + B Problem

    Write a function that add two numbers A and B. Of course ...

  • ACM(eight)

    A + B Problem Too This problem is also a A + B problem,bu...

  • HDU 2101 A + B Problem Too

    Problem Description This problem is also a A + B problem,...

  • A + B Problem

    Description:Input and output are the same with problem 10...

  • A + B Problem

    输入多组数据,将输入作为判断的条件。 定义两个整型变量作为A,B,然后进行数学计算,输出两者之和。 https:/...

  • A + B Problem

    InputEach line will contain two integers A and B. Process...

  • A+B Problem too

    This problem is also a A + B problem,but it has a little ...

  • A + B Problem Too

    This problem is also a A + B problem,but it has a little ...

  • 8

    This problem is also a A + B problem,but it has a little ...

网友评论

      本文标题:lint0001 A + B Problem

      本文链接:https://www.haomeiwen.com/subject/ssxmsqtx.html