将字符串解释为数字 —— Parse string to number

解释带符号整数

TODO: 补充介绍和所使用的算法。

def parse_int(s):

  # handle negative number
  if s[0] == '-':
    negative = True
    s = s[1:]
  else:
    negative = False

  result = 0

  for c in s:
    if result != 0: result *= 10
    result += int(c)

  if negative:
    return -result
  else:
    return result


if __name__ == "__main__":

    # zero
    assert parse_int(str(0)) == 0

    # non-zero and non-negative
    assert parse_int(str(123)) == 123

    # negative
    assert parse_int(str(-123)) == -123

留言

comments powered by Disqus

Table Of Contents

Previous topic

指数补偿 —— Exponential backoff

Next topic

On Building Systems That Will Fail 笔记