// refer to // https://leetcode.com/discuss/111582/java-simple-easy-understand-solution-with-explanation class Solution { public: int getSum(int a, int b) { //int tmp_sum = a ^ b; // a xor b //int tmp_carry = a & b << 1; // (a & b) << 1 while (b != 0) { int tmp_carry = a & b; a = a ^ b; // a xor b b = tmp_carry << 1; } return a; } };
本文介绍了一种使用位运算实现两整数相加的算法。该算法避免了使用加法运算符,通过不断进行异或和与操作左移,直至进位为0来计算两个整数的和。
218

被折叠的 条评论
为什么被折叠?



