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

การแยกตัวเลขเป็นชุดที่มีตัวเลขคู่หรือคี่ติดกันใน JavaScript

ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลข n (n > 0) ฟังก์ชันควรคืนค่าอาร์เรย์ที่มีส่วนติดต่อกันของตัวเลขคู่หรือคี่ หมายถึง ต้องแยกตัวเลขที่ตำแหน่งที่เจอตัวเลขประเภทต่างกัน (คู่→คี่ หรือ คี่→คู่)

ตัวอย่าง

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

const num = 124579;
const splitDifferent = (num = 1) => {
  const str = String(num);
  const res = [];
  let temp = '';
  for (let i = 0; i < str.length; i++) {
    const el = str[i];
    if (!temp || +temp[temp.length - 1] % 2 === +el % 2) {
      temp += el;
    } else {
      res.push(+temp);
      temp = el;
    }
  }
  if (temp) {
    res.push(+temp);
    temp = '';
  }
  return res;
};
console.log(splitDifferent(num));

ผลลัพธ์

[ 1, 24, 579 ]

คำอธิบายเพิ่มเติม

จาก 124579: 1(คี่) แยก 24(คู่คู่) แยก 579(คี่คี่คี่) โค้ดเปรียบเทียบ parity (คู่/คี่) ของหลักสุดท้ายของ temp กับหลักปัจจุบัน