Mô tả vấn đề
Chúng ta cần viết hàm JavaScript nhận vào chuỗi str và số n. Hàm thay đổi chuỗi dùng n: mỗi bit trong n quy định có đổi chữ hoa/thường cho ký tự chữ cái tiếp theo không. Bit 1 = đổi, 0 = giữ nguyên. Khi hết bit, quay lại bit đầu.
Ví dụ minh họa
Mã thực hiệ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));Đầu ra
Kết quả trong console:
HeY TheRe