LeetCode Notes 002

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = “11”
b = “1”
Return “100”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @param {string} a
* @param {string} b
* @return {string}
*/

var addBinary = function(a, b) {
a = a.split('').reverse();
b = b.split('').reverse();

var c = [];
var add = 0;

for(var i = 0, len = Math.max(a.length, b.length);i < len; i++) {
var sum = (a[i] === undefined ? 0 : Number(a[i])) + (b[i] === undefined ? 0: Number(b[i])) + add;
c[i] = sum & 1;
if (sum >= 2)
add = 1;
else
add = 0;
}

if (add)
c[len] = 1;

return c.reverse().join('').toString();
};

Add Digit

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
while(num.toString().length !== 1) {
var sum = 0;
while (num) {
sum += num % 10;
num = ~~(num / 10);
}
num = sum;
}

return num;
};

Add Strings

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = function(num1, num2) {
let [i, j] = [num1.length, num2.length];
let ans = '';
let add = 0;

i -= 1, j -= 1;
for ( ; i >= 0 || j >= 0; i--, j--) {
let a = i >= 0 ? +num1[i] : 0;
let b = j >= 0 ? +num2[j] : 0;
let sum = a + b + add;
ans = sum % 10 + ans;
add = ~~(sum / 10);
}

add && (ans = add + ans);
return ans;
};
文章作者: Monad Kai
文章链接: onlookerliu.github.io/2017/12/30/LeetCode-Notes-002/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏