ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง str และตัวเลข n ฟังก์ชันของเราควรเปลี่ยนสตริงที่กำหนดโดยใช้ n
แต่ละบิตใน n จะระบุว่าจะสลับตัวพิมพ์ของตัวอักษรแต่ละตัวใน s หรือไม่ −
หากบิตเป็น 1 ให้สลับเคส หากเป็น 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