เราต้องเขียนฟังก์ชันที่รับตัวเลขและคืนตัวเลขที่เล็กที่สุดที่สามารถสร้างได้จากการจัดเรียงเลขหลัก โดยห้ามใช้เมธอดสตริงและอาร์เรย์
ตัวอย่าง: 614532 → 123456
ตัวอย่างโค้ด
const num = 614532;
const sortDigits = num => {
const getDigit = e => Math.floor(num / 10 ** e) % 10;
const l = Math.ceil(Math.log10(num)) - 1;
let e = l;
while (e--) {
const left = getDigit(e + 1);
const right = getDigit(e);
if (left <= right) { continue; }
num += (right - left) * 9 * 10 ** e;
e = l;
}
return num;
};
console.log(sortDigits(num));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
123456