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

การหาค่าตำแหน่ง (Place Value) ของตัวเลขใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีแยกตัวเลขออกเป็นค่าตำแหน่ง (Place Values) โดยใช้ Recursive Function เช่น 1234 -> [1000, 200, 30, 4]

การนำไปใช้ (Recursive)

const splitNumber = (num, arr = [], m = 1) => {
  if (num) {
    return splitNumber(
      Math.floor(num / 10), 
      [m * (num % 10)].concat(arr), 
      m * 10
    );
  }
  return arr;
};

console.log(splitNumber(2346));  // [2000, 300, 40, 6]
console.log(splitNumber(5664));  // [5000, 600, 60, 4]
console.log(splitNumber(3453));  // [3000, 400, 50, 3]
console.log(splitNumber(2));     // [2]
console.log(splitNumber(657576)); // [600000, 50000, 7000, 500, 70, 6]

ผลลัพธ์

[ 2000, 300, 40, 6 ]
[ 5000, 600, 60, 4 ]
[ 3000, 400, 50, 3 ]
[ 2 ]
[ 600000, 50000, 7000, 500, 70, 6 ]
[ 300000, 40000, 5000, 200, 30, 2 ]

วิธีการแบบ Iterative (เข้าใจง่ายกว่า)

const splitNumberIterative = (num) => {
  const result = [];
  let factor = 1;
  
  while (num > 0) {
    const digit = num % 10;
    result.unshift(digit * factor);
    num = Math.floor(num / 10);
    factor *= 10;
  }
  
  return result.length > 0 ? result : [0];
};

วิธีการทันสมัย (Functional)

const splitNumberModern = (num) => 
  String(num)
    .split('')
    .map((digit, i, arr) => Number(digit) * Math.pow(10, arr.length - 1 - i));

การประยุกต์ใช้

  • การสอนคณิตศาสตร์ (Place Value Education)
  • Number Formatting (เช่น 1,234,567)
  • Checksum Calculation (ISBN, Credit Card)
  • การแปลงฐานตัวเลข (Base Conversion)

ข้อควรระวัง

  • Recursive อาจเกิด Stack Overflow กับตัวเลขใหญ่มาก (หลักมากกว่า ~10,000 หลัก)
  • JavaScript จัดการตัวเลขได้แม่นยำถึง 2⁵³ - 1 (Number.MAX_SAFE_INTEGER)
  • ตัวเลขติดลบ: ต้องจัดการแยก (ใช้ Math.abs แล้วใส่เครื่องหมายทีหลัง)

เวอร์ชันรองรับ BigInt

const splitNumberBigInt = (num) => {
  const str = num.toString();
  return str.split('').map((digit, i, arr) => 
    BigInt(digit) * 10n ** BigInt(arr.length - 1 - i)
  );
};