[Leetcode] 8. String to integer (atoi)

subject

describe

Please realize one   myAtoi(string s)   Function to convert a string into a 32-bit signed integer (similar to the atoi function in C/C + +).

function   The algorithm of myAtoi(string s) is as follows:

Read in the string and discard useless leading spaces
Check whether the next character (assuming it has not reached the end of the character) is a positive or negative sign, and read the character (if any). Determines whether the final result is negative or positive. If neither exists, the result is assumed to be positive.
Reads the next character until the next non numeric character is reached or the end of the input is reached. The rest of the string will be ignored.
Convert these numbers read in the previous steps into integers (i.e., "123" - > 123, "0032" - > 32). If no number is read in, the integer is 0. Change the symbol if necessary (starting from step 2).
If the number of integers exceeds the 32-bit signed integer range [− 231,    two hundred and thirty-one   − 1], you need to truncate this integer to keep it within this range. Specifically, integers less than − 231 should be fixed to − 231 and greater than 231   The integer of − 1 should be fixed to 231   − 1 .
Returns an integer as the final result.
be careful:

The white space character in this question only includes the white space character ''.
Do not ignore any characters other than the leading space or the rest of the string after the number.

Example 1

Input: s = "42"
Output: 42
 Explanation: the bold string is the character that has been read in, and the caret is the character that is currently read.
Step 1:"42"(No characters are currently read in because there are no leading spaces)
         ^
Step 2:"42"(No characters are currently read in because they do not exist here '-' perhaps '+')
         ^
Step 3:"42"(Read in "42")
           ^
The integer 42 is parsed.
because "42" In scope [-2**31, 2**31 - 1] The final result was 42.

Example 2

Input: s = "   -42"
Output:-42
 Explanation:
Step 1:"   -42"(Read leading spaces but ignore them)
            ^
Step 2:"   -42"(Read in '-' Character, so the result should be negative)
             ^
Step 3:"   -42"(Read in "42")
               ^
Parse to get an integer -42 . 
because "-42" In scope [-2**31, 2**31 - 1] The final result is -42 . 

Example 3

Input: s = "4193 with words"
Output: 4193
 Explanation:
Step 1:"4193 with words"(No characters are currently read in because there are no leading spaces)
         ^
Step 2:"4193 with words"(No characters are currently read in because they do not exist here '-' perhaps '+')
         ^
Step 3:"4193 with words"(Read in "4193"ï¼›Read in stops because the next character is not a number)
             ^
The integer 4193 is parsed.
because "4193" In scope [-2**31, 2**31 - 1] The final result was 4193.

  Example 4

Input: s = "words and 987"
Output: 0
 Explanation:
Step 1:"words and 987"(No characters are currently read in because there are no leading spaces)
         ^
Step 2:"words and 987"(No characters are currently read in because they do not exist here '-' perhaps '+')
         ^
Step 3:"words and 987"(Due to the current character 'w' Is not a number, so read in stops)
         ^
The integer 0 was parsed because no number was read in.
Because 0 is in range [-2**31, 2**31 - 1] Within, the final result is 0.

  Example 5

Input: s = "-91283472332"
Output:-2147483648
 Explanation:
Step 1:"-91283472332"(No characters are currently read in because there are no leading spaces)
         ^
Step 2:"-91283472332"(Read in '-' Character, so the result should be negative)
          ^
Step 3:"-91283472332"(Read in "91283472332")
                     ^
Parse to get an integer -91283472332 . 
because -91283472332 Less than range [-2**31, 2**31 - 1] The final result is truncated to -2**31 = -2147483648 . 

Tips

(1)0 <= s.length <= 200

(2)s   It consists of English letters (uppercase and lowercase), numbers (0-9), ',' + ',' - '   and  '.'  form

Problem solving ideas

(1) Conversion rules for enumerating strings

(2) The first character is "+", "-", a number. If it is read, it is a space. If it is in English, it will enter the next character, and if it is other, it will return 0

(3) If the number read is not continuous, return where there is no continuity

(4) If the output result is greater than 2 * * 31-1, then 2 * * 31-1 will be output, and if it is less than - 2 * * 31, then - 2 * * 31 will be output

code

class Solution:
    def myAtoi(self, s: str) -> int:
        def get_num(num):
            if int(num) < -2**31:
                return -2**31
            elif int(num)>2**31-1:
                return 2**31-1
            else:
                return int(num)
        def get_new_s(s):
            if len(s)!=0:
                if s[0]==" ":
                    return get_new_s(s[1:])
            return s

        start = 0
        num = ""
        
        s = get_new_s(s)
        for i, char in enumerate(s):
            if i==0:
                if char in ("+", "-") or char.isdigit():
                    num = num + char
                    start = 1
                else:
                    return 0
            elif char.isdigit():
                num = num + char
                start = 1
            elif start == 1 and not char.isdigit():
                if num in ("+", "-"):
                    return 0
                return get_num(num)
        if num in ("", "+", "-"):
            return 0
        return get_num(num)

Reference

Question bank leetcode is the technology growth platform loved by geeks all over the world

Tags: Python Algorithm data structure leetcode Interview

Posted on Tue, 14 Sep 2021 16:32:49 -0400 by sqishy