Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to convert the first character of the string to an integer.
DSA Javascript
const str = "123"; const num = parseInt(str[1]); console.log(num);
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets to access characters.
Using index 1 instead of 0 to get the first character.
✗ Incorrect
Using str[0] accesses the first character of the string, which parseInt converts to an integer.
2fill in blank
mediumComplete the code to skip leading spaces before converting string to integer.
DSA Javascript
const str = " 42"; const trimmed = str[1](); const num = parseInt(trimmed); console.log(num);
Attempts:
3 left
💡 Hint
Common Mistakes
Using trimEnd() which removes trailing spaces instead.
Using trim() which removes spaces from both ends.
✗ Incorrect
trimStart() removes spaces from the start of the string, so parseInt reads the number correctly.
3fill in blank
hardFix the error in the code to correctly parse the integer from the string with sign.
DSA Javascript
function myAtoi(str) {
let i = 0;
let sign = 1;
if (str[i] === '-' || str[i] === '+') {
sign = str[1] === '-' ? -1 : 1;
i++;
}
let num = 0;
while (i < str.length && str[i] >= '0' && str[i] <= '9') {
num = num * 10 + (str[i].charCodeAt(0) - '0'.charCodeAt(0));
i++;
}
return sign * num;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets to access characters.
Using a fixed index like 0 instead of current index i.
✗ Incorrect
To check the sign character, use str[i] with square brackets to access the character at index i.
4fill in blank
hardFill both blanks to correctly check if a character is a digit and convert it to a number.
DSA Javascript
function charToDigit(c) {
if (c [1] '0' && c [2] '9') {
return c.charCodeAt(0) - '0'.charCodeAt(0);
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using equality operators instead of range comparisons.
Reversing the comparison operators.
✗ Incorrect
To check if c is between '0' and '9', use c >= '0' and c <= '9'.
5fill in blank
hardFill all three blanks to build a dictionary of characters and their integer values for digits 0-9.
DSA Javascript
const digitMap = {
[1]: [2],
[3]: 1
};Attempts:
3 left
💡 Hint
Common Mistakes
Using numbers as keys without quotes.
Mixing string and number types incorrectly.
✗ Incorrect
Keys are string digits like '0' and '1', values are numbers 0 and 1.
