leetcode 371. Sum of Two Integers 位运算 + 加法操作

谁借莪1个温暖的怀抱¢ 2022-06-07 02:46 282阅读 0赞

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.

这道题考察的是两个数的加法,但是不允许使用加法运算,我感觉应该使用位运算,但是想不到,网上看到了一个做法,很不错,值得学习。

代码如下:

  1. /*
  2. * 这是网上的做法,很奇妙,我能猜到使用位运算去做,但是不会
  3. */
  4. public class Solution
  5. {
  6. public int getSum(int a, int b)
  7. {
  8. while (b != 0)
  9. {
  10. int carry = (a & b) << 1;
  11. a = a ^ b;
  12. b = carry;
  13. }
  14. return a;
  15. }
  16. }

下面是C++的做法

就直接使用加法吧

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. using namespace std;
  19. class Solution
  20. {
  21. public:
  22. int getSum(int a, int b)
  23. {
  24. return a + b;
  25. }
  26. };

发表评论

表情:
评论列表 (有 0 条评论,282人围观)

还没有评论,来说两句吧...

相关阅读