Atoi

class Solution:
    # @param A : string
    # @return an integer
    def atoi(self, A):
        mx = (2**31)-1
        mn = -(2**31)
        s = ''
        for x in A:
            if x.isdigit() or (A.index(x)==0 and x in ('-', '+')):
                s += x
            else:
                break
 
        if (s and s[0].isdigit()) or (len(s)>1 and s[0] in ('+', '-')):
            if 0 <= int(s) <= mx: return int(s) 
            elif mn < int(s) < 0: return int(s)
            elif int(s) < mn : return mn
            else: return mx
        else:
            return 0


Trivia:
1. Written in Python 3.
2. Runs in constant time and space.
3. Takes care of corner cases, because only them needs to be taken care of.

Problem statement: Implement atoi to convert a string to an integer.

Input : "9 2704"
Output : 9
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s