数字根算法 JavaScript
某些正整数的数字根的定义为其所有数字的数字之和。我们获得了一个整数数组。我们必须按以下方式对它排列:如果 a 在 b 之前,则当 a 的数字根小于或等于 b 的数字根时。如果两个数字的数字根相同,则较小的数字(按常规意义)应排在前面。例如,4 和 13 的数字根相同,但是 4 < 13,因此在有这两个数字的任何数字根排列中,4 都应排在 13 之前。
例如,
for a = [13, 20, 7, 4], the output should be [20, 4, 13, 7].
让我们编写对此问题的代码 −
我们将把代码分为两个函数:一个计算数字数字之和的递归函数,然后是一个根据数字之和对元素排序的排序函数。
代码如下 −
示例
const arr = [54, 23, 8, 89, 26];
const recursiveCount = (num, count = 0) => {
if(num){
return recursiveCount(Math.floor(num/10), count+num%10);
};
return count;
};
const sorter = (a, b) => {
const countDifference = recursiveCount(a) - recursiveCount(b);
return countDifference || a - b;
};
arr.sort(sorter);
console.log(arr);输出
在控制台中的输出为 −
[ 23, 8, 26, 54, 89 ]
Advertisements
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP