Trọng số ký tự = vị trí 1-based trong alphabet (a=1, b=2...). Viết hàm tính tổng trọng số chuỗi chữ thường.
Ví dụ: 'this is a string' → 172.
Ví dụ
const str = 'this is a string';
const calculateWeight = (str = '') => {
str = str.toLowerCase();
const legend = 'abcdefghijklmnopqrstuvwxyz';
let weight = 0;
const { length: l } = str;
for (let i = 0; i < l; i++) {
const curr = legend.indexOf(str[i]);
weight += (curr + 1);
}
return weight;
};
console.log(calculateWeight(str));
Kết quả
172