LeetCode 371. Sum of Two Integers

    xiaoxiao2021-03-25  112

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

    思路: 其实就是模拟进位 1.首先最低位相加是要进一的 2.然后在做第二位的运算 3.以此类推,一直到没有进位为止。

    代码:

    class Solution { public: int getSum(int a, int b) { while(a != 0) { int tmp = (a & b) << 1; b = a ^ b; a = tmp; } return b; } };
    转载请注明原文地址: https://ju.6miu.com/read-9083.html

    最新回复(0)