Skip to content

Instantly share code, notes, and snippets.

@akost
Last active July 2, 2017 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akost/ec0df6ea1bd3af4ac35191d88ab3d162 to your computer and use it in GitHub Desktop.
Save akost/ec0df6ea1bd3af4ac35191d88ab3d162 to your computer and use it in GitHub Desktop.
Convert string to signed integer
"""
Convert string to integer
"""
import unittest
class TestStringMethods(unittest.TestCase):
def test1(self):
self.assertEqual(myInt("123"), 123)
def test2(self):
self.assertEqual(myInt("-1"), -1)
def test3(self):
self.assertEqual(myInt("0"), 0)
def test4(self):
self.assertEqual(myInt("-0"), 0)
def test5(self):
self.assertRaises(TypeError, myInt, "")
def test6(self):
self.assertRaises(TypeError, myInt, "12q3")
def myInt(s):
num = 0
if len(s) == 0:
raise TypeError("String must be non-empty")
sign = 1
if s[0] == "-":
sign = -1
s = s[1:]
power = 0
for i in range(len(s)-1, -1, -1):
if ord(s[i]) in range(ord("0"), ord("9")+1):
num += (ord(s[i]) - ord("0")) * 10**power
power += 1
else:
raise TypeError("String must contain only digits and minus sign")
return sign * num
unittest.main()
print myInt("-112490") # -112490
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment