Skip to content

Instantly share code, notes, and snippets.

@sunqiang
Created October 29, 2010 02:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sunqiang/652769 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: atoi.py
def atoi(s = ' \t\n-630x'):
""" atoi, convert a string to int.
>>> atoi()
-630
>>> atoi('+0630119')
630119
"""
result = 0
length = len(s)
i = 0
while i < length and s[i].isspace():
i += 1
sign = - 1 if s[i] == '-' else 1
if s[i] == '-' or s[i] == '+':
i += 1
while i < length and s[i].isdigit():
result = result * 10 + (ord(s[i]) - ord('0'))
i += 1
result *= sign
return result
if __name__ == "__main__":
print atoi() # -> -630
print atoi('+0630119') # -> 630119
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment