leetcode 371. 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.
这道题考察的是两个数的加法,但是不允许使用加法运算,我感觉应该使用位运算,但是想不到,网上看到了一个做法,很不错,值得学习。
代码如下:
/*
* 这是网上的做法,很奇妙,我能猜到使用位运算去做,但是不会
*/
public class Solution
{
public int getSum(int a, int b)
{
while (b != 0)
{
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}
下面是C++的做法
就直接使用加法吧
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
int getSum(int a, int b)
{
return a + b;
}
};
还没有评论,来说两句吧...