Leetcode String to Integer (atoi)

来源:互联网 发布:it好不好学 编辑:程序博客网 时间:2024/06/14 01:19

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.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.


class Solution:    def atoi(self, str):        lens = len(str);                if lens == 0:            return 0;                i = 0;        cnt = 1;        sum = 0;                while i < lens:            if str[i] == ' ':                i += 1;            else:                break;                    if str[i] == '-':            cnt = -1;            i += 1;        elif str[i] == '+':            cnt = 1;            i += 1;        elif str[i] < '0' or str[i] > '9':            return 0;                while i < lens and str[i] >= '0' and str[i] <= '9':            sum = sum * 10 + ord(str[i])-ord('0');            i += 1;                sum = sum*cnt;                if sum > 0x7fffffff:            sum = 0x7fffffff;        if sum < -2 ** 31:            sum = -2 ** 31;        return sum;


0 0
原创粉丝点击