ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลข n ฟังก์ชันต้องคืนค่าค่าสูงสุดโดยการจัดเรียงหลักตัวเลขใหม่
ตัวอย่าง
โค้ดตัวอย่างด้านล่าง:
const num = 124;
const rotateToMax = n => {
n = n
.toString()
.split('')
.map(el => +el);
n.sort((a, b) => {
return b - a;
});
return n.join('');
};
console.log(rotateToMax(num));
ผลลัพธ์
421
คำอธิบายเพิ่มเติม
แปลงเป็น array of digits, sort descending, join กลับ 124 → [1,2,4] → sort desc [4,2,1] → "421" ชื่อฟังก์ชัน rotateToMax ผิดนัย (rotate ≠ permute) ควรเป็น rearrangeToMax หรือ maxPermutation