JonnyF--String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

解题思路:

       这道题是将字符窜转换成数字,因此只需要主要下面几点就好了。
       1.数字前面有空格 如s=“    123456”
       2.数字前出现了不必要或多于的字符导致数字认证错误,输出0   如s=“   b1234”  ,s=“  ++1233” , s=“ +-1121”
       3.数字中出现了不必要的字符,返回字符前的数字 如s=“   12a12” , s=“ 123  123”
       4.数字越界 超过了范围(-2147483648--2147483647) 若超过了负数的 输出-2147483648  超过了正数的输出2147483647

class Solution:
    # @param str, a string
    # @return an integer
    def myAtoi(self, str):
        if str == '':
            return(0)
        str = list(str)
        result = []
        positive = negtive = 0
        has_digit = False
        for i in range(len(str)):
            if str[i] != '-' and str[i] != '+' and str[i].isdigit() == False and str[i] != ' ':
                if has_digit is False:
                    return(0)
                else:
                    break
            if str[i] == ' ' and has_digit:
                break
            if str[i] == ' ' and (negtive or positive):
                return(0)
            if str[i] == '-':
                negtive = negtive + 1
            if str[i] == '+':
                positive = positive + 1
            if negtive > 1 or positive > 1 or (negtive == 1 and positive == 1):
                return(0)
            if str[i].isdigit():
                has_digit = True
                result.append(str[i])
        result = ''.join(result)
        if negtive:
            result = '-' + result
        if has_digit:
            if int(result) > 2**31 - 1:
                return(2147483647)
            if int(result) < -2**31:
                return(-2**31)
            return(int(result))
        else:
            return(0)
posted @ 2015-05-14 14:27  F-happy  阅读(108)  评论(0)    收藏  举报