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的实现,用数组下标代替,不需要回溯,只要处理好各种异常情况。

  • 相关阅读:
    android 中 Canvas和Paint
    【30篇突击 android】源码统计 十五
    【eoe特刊】第二十七期 OpenGL ES学习及项目解析
    java项目打jar包
    用Think Pad 系统升级程序ThinkVantage System Update时候提示 无法连接代理服务器 的解决办法
    asp.net中部打开新页面下载文件
    java混淆器proguard的一些资料
    flex中接收非utf8编码的后台数据
    Win2003 sp2 下安装IIS,会提示找不到iisadmin.mfl等文件无法继续安装的解决方法
    windows下部能用域名访问网址或共享文件夹的解决方法
  • 原文地址:https://www.cnblogs.com/openqt/p/4039324.html
Copyright © 2011-2022 走看看