实现 sum(1,2)(3).sumOf() === 6
都是泪呀,竟然没写出来,过后发现其实之前不难,以此谨记~
1 2 3 4 5 6 7 8 9 10 11
| function sum() { let args = [...arguments]; let add = function() { args.push(...arguments); return add; } add.sumOf = function() { return args.reduce((acc, cur) => acc + cur); } return add; }
|
算法题 从长度为 N 的 arr 数组中取 count 个数相加总和为 sum
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
const search = (arr, count, sum) => { const n = num => { let count = 0; while (num) { num &= num - 1; count++; } return count; }; let len = arr.length; let bit = 1 << len; let res = []; for (let i = 1; i < bit; i++) { if (n(i) === count) { let s = 0; let temp = []; for (let j = 0; j < len; j++) { if ((i & (1 << j)) !== 0) { s += arr[j]; temp.push(arr[j]); } } if (s === sum) { res.push(temp); } } } return res; };
|
评论加载中