Learn practical skills, build real-world projects, and advance your career

8. -string-to-integer-atoi

Use the "Run" button to execute the code.

!pip install jovian --upgrade --quiet
import jovian

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

The algorithm for myAtoi(string s) is as follows:

  1. Read in and ignore any leading whitespace.
  2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
  4. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
  5. If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2^31 should be clamped to -2^31, and integers greater than 2^31 - 1 should be clamped to 2^31 - 1.
  6. Return the integer as the final result.

Note:

Only the space character ' ' is considered a whitespace character. Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

def myAtoi(s):
    
    if s == "":
        return 0
    
    res = ""
    sign = 1
    n = len(s)
    digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    #whitespace
    for i in range(n):
        if s[i] == ' ':
            res = s[i + 1:]
        if s[0] != ' ':
            res = s
        
    print(res, len(res))
    
    #leadsign
    if res[0] == '-':
        res = res[1:]
        sign = -1   
    elif res[0] == '+':
        res = res[1:]
        
    print(res, sign, len(res))
    
    #digits
    for j in range(len(res)):
        print(j)
        if res[j] not in digits and j == 0:
            return 0
        if res[j] not in digits:
            r_int = int(res[:j]) * sign
            break
        else:
            r_int = int(res[:j + 1]) * sign
    
    
    #bounds
    if r_int < -2**31:
        r_int = -2**31
    if r_int > 2**31 - 1:
        r_int = 2**31 - 1
    
    
    
    return r_int
        

# having a lot of trouble with all the testcases just doing the brute force