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

การหา Gapful Number ที่ใกล้ที่สุดใน JavaScript

เลข Gapful Number คือเลขที่

  • มีอย่างน้อย 3 หลัก และ
  • หารด้วยเลขที่เกิดจากการนำตัวเลขหลักแรกและหลักสุดท้ายมารวมกัน ลงตัว

เช่น

เลข 1053 เป็น Gapful เพราะมี 4 หลัก และหารด้วย 13 ลงตัว เหมือนกัน 135 ก็เป็น Gapful เพราะมี 3 หลักและหารด้วย 15 ลงตัว

หน้าที่ของเราคือเขียนโปรแกรมคืนค่า Gapful Number ที่ใกล้ที่สุดกับตัวเลขที่รับเข้ามา

เช่น สำหรับเลข 2 หลักทุกตัว จะได้ 100 สำหรับ 103 จะได้ 105

เราจะแบ่งปัญหาเป็นสองฟังก์ชัน

ฟังก์ชัน isGapful()

รับสตริงตัวเลข คืนค่า boolean

const isGapful = (numStr) => {
  const int = parseInt(numStr);
  return int % parseInt(numStr[0] + numStr[numStr.length - 1]) === 0;
};

ฟังก์ชัน nearestGapful()

ฟังก์ชันหลัก รับตัวเลข คืนค่า Gapful Number ที่ใกล้ที่สุด

const nearestGapful = (num) => {
  if(typeof num !== 'number'){
    return -1;
  }
  if(num <= 100){
    return 100;
  }
  let prev = num - 1, next = num + 1;
  while(!isGapful(String(prev)) && !isGapful(String(next))){
    prev--;
    next++;
  };
  return isGapful(String(prev)) ? prev : next;
};

ฟังก์ชัน isGapful() คืนค่า boolean ในเวลาคงที่ ฟังก์ชัน nearestGapful() ลูปจนกว่าจะเจอ Gapful Number แล้วคืนค่า

โค้ดเต็ม

ตัวอย่าง

const n = 134;
const isGapful = (numStr) => {
  const int = parseInt(numStr);
  return int % parseInt(numStr[0] + numStr[numStr.length - 1]) === 0;
};
const nearestGapful = (num) => {
  if(typeof num !== 'number'){
    return -1;
  }
  if(num <= 100){
    return 100;
  }
  let prev = num - 1, next = num + 1;
  while(!isGapful(String(prev)) && !isGapful(String(next))){
    prev--;
    next++;
  };
  return isGapful(String(prev)) ? prev : next;
};
console.log(nearestGapful(n));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็น

135