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

สลับพิมพ์เล็ก-ใหญ่ของสตริงด้วยตัวเลข Binary ใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง str และตัวเลข n ฟังก์ชันควรเปลี่ยนสตริงที่ให้มาโดยใช้ n

แต่ละบิตใน n จะระบุว่าจะสลับ case สำหรับตัวอักษรแต่ละตัวใน s หรือไม่:

ถ้าบิตเป็น 1 ให้สลับ case ถ้าเป็น 0 ให้คงเดิม เมื่อจบบิตสุดท้ายของ n ให้เริ่มที่บิตแรกใหม่

สุดท้ายควรคืนสตริงใหม่ที่ได้

ตัวอย่าง

โค้ดด้านล่างนี้

const str = 'hey there'; 
const num = 21; 
const swapCase = (str = '', num = 1) => {
  const alphaLength = str
    .split('')
    .reduce((acc, val) => val.toLowerCase() !== val.toUpperCase() ? ++acc : acc, 0);
  let binary = num.toString(2);
  while(binary.length < alphaLength){
    binary += binary;
  }
  let res = '';
  for(let i = 0; i < str.length; i++){
    const el = str[i];
    if(el.toUpperCase() !== el.toLowerCase() && +binary[i] === 1){
      if(el.toLowerCase() === el){
        res += el.toUpperCase();
      }else{
        res += el.toLowerCase();
      }
    }else{
      res += el;
    }
  }
  return res;
};
console.log(swapCase(str, num));

ผลลัพธ์

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

HeY TheRe