LeetCode - Algorithms - 371. Sum of Two Integers

这题不Easy呀,像智力题,像脑筋急转弯。
代码是人家的,我可想不出来。真是“会者不难,难者不会”。

JavaScript

自增自减运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function(a, b) {
if (a>0) {
while(a>0) {
a--;
b++
}
}
if (a<0) {
while(a<0) {
a++;
b--;
}
}
return b;
};

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 3.38 % of javascript submissions.

位运算+递归

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function(a, b) {
var sum,carry;
if (b==0) return a;
sum = a^b;
carry = (a&b)<<1;
return getSum(sum,carry);
};

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 69.57 % of javascript submissions

消除递归的位运算

知其然而不知其所以然,居然可以这么做,觉得很神奇

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function(a, b) {
while(b!=0) {
var carry=a&b;
a = a^b;
b = carry<<1;
}
return a;
};

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 100.00 % of javascript submissions.

Java

消除递归的位运算

1
2
3
4
5
6
7
8
9
10
class Solution {
public int getSum(int a, int b) {
while (b!=0) {
int carry = a&b;
a = a^b;
b = carry<<1;
}
return a;
}
}

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 100.00 % of java submissions.

递归+位运算

1
2
3
4
5
6
7
8
9
class Solution {
public int getSum(int a, int b) {
int sum,carry;
if (b==0) return a;
sum = a ^ b;
carry = (a & b) << 1;
return getSum(sum,carry);
}
}

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 100.00 % of java submissions.

自增自减运算符

这个解很像脑筋急转弯,不难,但让人想不到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int getSum(int a, int b) {
if (a>0) {
while(a>0) {
a--;
b++;
}
}
if (a<0) {
while(a<0) {
a++;
b--;
}
}
return b;
}
}

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 3.44 % of java submissions.