1. 程式人生 > >LeetCode: 371 Sum of Two Integers(easy)

LeetCode: 371 Sum of Two Integers(easy)

pan per ret sum integer 計算 code 移位 etc

題目:

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位來算進位,然後將兩者相加。

1 class Solution {
2 public:
3     int getSum(int a, int b) {
4         return b == 0 ? a : getSum(a^b, (a&b)<<1
); 5 } 6 };

什麽樣的數據可以直接移位? char、 short、 int、 long、 unsigned char、 unsigned short、 unsigned int、 unsigned long

什麽樣的數據不能直接移位? double、 float、 bool、 long double

LeetCode: 371 Sum of Two Integers(easy)