LeetCode:Sum of Two Integers

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.

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

Subscribe to see which companies asked this question

Hide Tags
  Bit Manipulation
Hide Similar Problems
  (M) Add Two Numbers




















思路:

之前总结的:位操作实现加减乘除四则运算


c++ code:

class Solution {
public:
    int getSum(int a, int b) {
        int c; // 进位
        while(b) {
            c = (a & b) << 1;
            a = a ^ b;
            b = c;
        }
        return a;
    }
};


你可能感兴趣的:(LeetCode,bit,manipulation)