371. Sum of Two Integers

来源:互联网 发布:中日海军对比2017知乎 编辑:程序博客网 时间:2024/06/05 13:13

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.

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

在位操作中,a ^ b能得到进位,a & b能得到相加后还没加进位的数,上面两步一直循环,直到carry等于0,就能得到最后的结果。代码如下:

public class Solution {    public int getSum(int a, int b) {        if (a == 0) {            return b;        }        if (b == 0) {            return a;        }        while (b != 0) {            int carry = a & b;            a = a ^ b;            b = carry << 1;        }        return a;    }}

0 0
原创粉丝点击