首页 > 其他 > 详细

8. String to Integer (atoi)

时间:2018-08-18 12:38:44      阅读:145      评论:0      收藏:0      [点我收藏+]

技术分享图片

def solve(num_str):
    MAX, MIN = 65535, -65536
    num_str_len = len(num_str)
    i = 0
    while num_str[i] ==  :
        i += 1
    if i == num_str_len:
        return 0
    is_neg = True if num_str[i] == - else False
    i += 1
    ans = 0
    is_valid = True
    while i < num_str_len:
        if num_str[i] < 0 or num_str[i] > 9:
            print err
            is_valid = False
            break
        if not is_neg and ans > (MAX - (int(num_str[i]) - int(0))) / 10:
            return MAX
        if is_neg and ans > (-MIN - (int(num_str[i]) - int(0))) / 10:
            return MIN
        ans = ans * 10 + int(num_str[i]) - int(0)
        i += 1

    if is_valid:
        return ans if not is_neg else -ans
    return 0


print solve(   -65537fa)

 

8. String to Integer (atoi)

原文:https://www.cnblogs.com/geeklove01/p/9496594.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!