數字根演算法 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