分享

LeetCode之Sum of Two Integers

 陈喻 2021-10-19

1、题目

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.

Subscribe to see which companies asked this question.

2、代码实现

public class Solution {
    public int getSum(int a, int b) {
     while(b != 0)  
        {  
            int tmp =(a & b) << 1; 
            //a是每次相加,相当于和
            a = a ^ b;
            //b相当于是进位
            b = tmp;
        }  
        return a;  
     }
}

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多