เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้ตัวเลข ฟังก์ชันควรคืนค่าจำนวนที่น้อยที่สุดที่สามารถเกิดขึ้นได้จากการจัดเรียงตัวเลขของตัวเลขใหม่
ตัวอย่างเช่น −
หากหมายเลขอินพุตคือ −
const num = 614532;
จากนั้นผลลัพธ์ควรเป็น −
const output = 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