2020.3.8 Vivo笔试
第一次发帖,紧张
使用语言JavaScript
1、相当于计算数列 1,2,2,3,3,3,4,4,4,4,5……前n项的和
function solution(n) { const x = Math.floor(Math.sqrt(1 + 8 * n) / 2 - 0.5); const remain = n - ((1 + x) * x) / 2; let result = 0; for (let i = 1; i <= x; i++) { result += i ** 2; } result += remain * (x + 1); return result; }2、找出每位乘积为n的最小数,如36=>49(4*9=36),2=>12(1*2=2)
function solution(n) { let result = ''; let tmp = n; for (let i = 9; i > 1; i--) { while (!(tmp % i)) { tmp /= i; result = i + result; } } while (tmp === 1 && result.length < 2) { result = 1 + result; } if (tmp !== 1) { return -1; } else { return parseInt(result); } }3、给定最大长度n和最小长度m,求锁屏图案密码的总数。其实就是找有多少个长度在m到n之间的符合规则的点序列。
/* 1 2 3 4 5 6 7 8 9 */ function isCorrect(path, point) { const lines = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7] ]; if (path.length === 0) { return true; } if (path.indexOf(point) !== -1) { return false; } let point1 = path[path.length - 1]; let point2 = point; if (point2 < point1) { [point1, point2] = [point2, point1]; } for (let line of lines) { if ( point1 === line[0] && point2 === line[2] && path.indexOf(line[1]) === -1 ) { return false; } } return true; } function solution(m, n) { let count = 0; function solve(path, remain) { if (remain <= max - min) { count++; } if (remain === 0) { return; } for (let i = 1; i <= 9; i++) { if (isCorrect(path, i)) { path.push(i); solve(path, remain - 1); path.pop(); } } } const min = Math.max(1, m); const max = Math.min(9, n); let path = []; solve(path, max); return count; }
不过上面能过的话下面的解也能过(而且肯定快,不过你要把每一项先算出来emmm)
function solution(m, n) { const result = [9, 56, 320, 1624, 7152, 26016, 72912, 140704, 140704]; const min = Math.max(1, m); const max = Math.min(9, n); return result.slice(min - 1, max).reduce((pre, cur) => pre + cur, 0); }