zoukankan      html  css  js  c++  java
  • 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.

    spoilers alert... click to show requirements for atoi.

    Requirements for atoi:

    The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

    The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

    If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

    If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

    分析:

    字符串转整数。这个问题如果用C/C++来做,代码可以写得很漂亮,用Python就略有些难看。一个比较诡异的地方是即使Python没有最大最小整数限制,这个题目仍然要求处理溢出的情况。这在Python里面也就是最后添加两个判断,但是对于C/C++语言来说需要额外处理好。

    class Solution:
        INT_MAX = 2147483647
        INT_MIN = -2147483648
    
        # @return an integer
        def atoi(self, str):
            if not str or len(str) == 0:
                return 0
    
            i = 0
            while str[i] == ' ':
                i += 1
    
            val = 0
            sign = False
            if str[i] == '-':
                sign = True
                i += 1
            elif str[i] == '+':
                i += 1
    
            for i in range(i, len(str)):
                c = str[i]
                if '0' <= c <= '9':
                    val = val * 10 + (ord(c) - ord('0'))
                else:
                    break
    
            if sign:
                val = -val
                val = max(val, Solution.INT_MIN)
            else:
                val = min(val, Solution.INT_MAX)
    
            return val
    
    if __name__ == '__main__':
        s = Solution()
        assert s.atoi('1234') == 1234
        assert s.atoi('-347') == -347
        assert s.atoi('+-2') == 0
        assert s.atoi('+1') == 1
        assert s.atoi(' 010') == 10
        assert s.atoi('2147483648') == 2147483647
        assert s.atoi('-2147483648') == -2147483648
        print 'PASS'

    小结:

    C语言可以用指针,Python里面我尽量仿照C的实现,用数组下标代替,不需要回溯,只要处理好各种异常情况。

  • 相关阅读:
    WCF、Net remoting、Web service概念及区别
    新浪微博技术架构分析
    谈SOA和云的分层架构
    开发人员眼中最好的代码编辑器是什么?
    调试脚本,远离alert
    struts2与cookie实现自动登录和验证码验证
    把旧的项目改变名称重新部署到tomcat下发现项目名称还是原来的项目名称,解决方案
    myeclipse2014 安装maven3.3.9和mave配置本地仓库
    mysql在表的某一位置增加一列、删除一列、修改列名
    Java实现对cookie的增删改查
  • 原文地址:https://www.cnblogs.com/openqt/p/4039324.html
Copyright © 2011-2022 走看看