我们需要编写一个以正整数(例如n)作为唯一参数的JavaScript函数。
该函数应首先将1到n的整数分组到子数组,其中特定的子数组包含所有元素,其中的所有元素包含特定的数字总和。然后,函数应检查每个子数组并返回包含最多元素的子数组的长度。
例如-
如果输入号码是-
const num = 15;
那么输出应该是-
const output = 2;
因为组是-
[1, 10], [2, 11], [3, 12], [4, 13], [5, 14], [6, 15], [7], [8], [9]
以下是代码-
const num = 67; const countLargestGroup = (num = 1) => { if(num < 10){ return num; }; let res = 0; let temp = 0; let map = {}; for(let i = 1; i <= num; i++){ let sum = 0; let num = i; while (num) { sum += num % 10; num = Math.floor(num / 10); } if(map[sum] != undefined){ map[sum]++; } else { map[sum] = 1; } }; for (const key of Object.keys(map)) { if(temp == map[key]){ res++; } else if(temp < map[key]){ res = 1; temp = map[key]; } }; return res; }; console.log(countLargestGroup(num));输出结果
以下是控制台输出-
4