0
0
DSA Pythonprogramming~10 mins

String to Integer atoi in DSA Python - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to convert the first character of the string to an integer digit.

DSA Python
digit = ord(s[0]) - [1]
Drag options to blanks, or click blank then click option'
A97
B65
C48
D32
Attempts:
3 left
💡 Hint
Common Mistakes
Using ASCII code of 'A' or 'a' instead of '0'.
Forgetting to subtract the ASCII code.
2fill in blank
medium

Complete the code to check if the character is a digit.

DSA Python
if '0' <= s[i] [1] '9':
Drag options to blanks, or click blank then click option'
A<
B==
C>=
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of <=.
Using > instead of <=.
3fill in blank
hard

Fix the error in the code to correctly build the integer from the string digits.

DSA Python
num = num [1] 10 + (ord(s[i]) - ord('0'))
Drag options to blanks, or click blank then click option'
A*
B-
C+
D//
Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of * for shifting digits.
Using // or - which are incorrect here.
4fill in blank
hard

Fill both blanks to correctly handle the sign and start index for parsing.

DSA Python
sign = 1
if s[0] == [1]:
    sign = -1
    i = [2]
else:
    i = 0
Drag options to blanks, or click blank then click option'
A'-'
B'+'
C1
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' for sign check.
Not updating the start index after sign.
5fill in blank
hard

Fill all three blanks to complete the atoi function that converts string to integer.

DSA Python
def my_atoi(s):
    s = s.strip()
    if not s:
        return 0
    sign = 1
    i = 0
    if s[0] == [1]:
        sign = -1
        i = 1
    elif s[0] == [2]:
        i = 1
    num = 0
    while i < len(s) and '0' <= s[i] <= '9':
        num = num [3] 10 + (ord(s[i]) - ord('0'))
        i += 1
    return sign * num
Drag options to blanks, or click blank then click option'
A'-'
B'+'
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Not handling '+' sign.
Using '+' instead of '*' when building the number.