Leetcode - String to Integer (atoi)

Ji Kim·2020년 10월 7일
0

Algorithm

목록 보기
25/34

Leetcode : String to Integer (atoi)

Description

Implement atoi which converts a string to an integer.

Constraints

  • Only the space character ' ' is considered a whitespace character.
  • Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1

Input

str = "42"

Output

42

Example 2

Input

str = "   -42"

Output

-42
// The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.

Example 3

Input

str = "4193 with words"

Output

4193
// Conversion stops at digit '3' as the next character is not a numerical digit

Example 4

Input

str = "words and 987"

Output

0
// The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5

Input

str = "-91283472332"

Output

-2147483648
// The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.

Approach

Generate the input - str based on the type of first element. Strip the first whitespaces, and distinguish if the first element is integer, character or numerical signs.

Solution (Python)

class Solution(object):
    def myAtoi(self, str):
        str = str.lstrip()
        flag = True
        result = 0
        length = len(str)
        times = 1
        
        if len(str) == 0:
            return 0 
        
        if str[0] == "-":
            flag = False
            str = str[1:length]
            length = length - 1
        elif str[0] == "+":
            str = str = str[1:length]
            length = length - 1

        try:
            type(int(str[0])) == type(1)
        except:
            return 0


        for i in range(0, length):
            try:
                type(int(str[i])) == type(1)
                #312009
                adder = int(str[i])

                result = (result * times) + adder
                times = 10
            except:
                break


        if result >= math.pow(2, 31) and flag == True:
            return 2147483647
        elif result >= math.pow(2, 31) and flag == False:
            return -2147483648

        if flag == True:
            return result
        else:
            result = result * -1
            return result

Result

Runtime: 28 ms
Memory Usage: 13.7 MB
Runtime Beats 46.71% of Python Submission

profile
if this then that

0개의 댓글