/** * @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:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
/** * @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); }