Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ตัวเลขน้อยที่สุดจากการสลับหลักได้สูงสุด 1 ครั้งใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับจำนวนบวก n เราสามารถทำได้สูงสุด 1 ครั้ง: เลือกดัชนีของหลักหนึ่ง ลบหลักนั้นออก และแทรกกลับที่ตำแหน่งอื่นหรือเดิม เพื่อหาตัวเลขน้อยที่สุดที่ได้

ฟังก์ชันควรคืนค่าตัวเลขน้อยที่สุดนี้

ตัวอย่าง

โค้ดตัวอย่างดังนี้:

const num = 354166;
const smallestShuffle = (num) => {
  const arr = String(num).split('');
  const { ind } = arr.reduce((acc, val, index) => {
    let { value, ind } = acc;
    if(value > val){
      value = val;
      ind = index;
    };
    return { value, ind };
  }, { value: Infinity, ind: -1 });
  const [item] = arr.splice(ind, 1);
  arr.unshift(item);
  return Number(arr.join(''));
};
console.log(smallestShuffle(num));

ผลลัพธ์

ผลลัพธ์ในคอนโซล:

135466