Given an encoded string S, the decoded string is determined by reading each character and following the steps below:
- If the character is a letter, it is written directly onto the tape.
- If the character is a digit (denoted as d), the current tape is repeated d-1 more times in total.
The task is to find and return the K-th letter (1 indexed) in the decoded string for a given encoded string S and index K.
I have attached my solution which shows different output compared to the expected result. Can anyone please suggest what changes need to be made in my solution? Thank you in advance.
INPUT
decodeAtIndex ("vzpp636m8y", 2920)
Expected Output: "z"
Output I received: "p"
var decodeAtIndex = function(S, K) {
let res = '';
let hasNumber = false;
let number = '';
let i = 0;
while((i < S.length)) {
if(S[i] < 10) {
number = number + S[i];
hasNumber = true;
while(S[i + 1] < 10) {
number = number + S[++i];
}
}
if (hasNumber) {
let repeat = res.repeat(parseInt(number - 1));
res = `${res}${repeat}`;
hasNumber = false;
number = '';
} else {
res = `${res}${S[i]}`;
}
i++;
}
return res[K - 1];
};