Solution: Number of Digits
Contents
Solution: Number of Digits#
Write a function that returns the number of digits for a given integer number.
Rules#
Input: integer (
int
) number (+
or-
)Solve this challenge without using
strings
or anyexternal
package.The function must return a
integer
value corresponding to the number of digits of the input number.
Function definition#
def get_digits(n):
n = abs(n)
length = 1
i = 10
while True:
division = n/i
if division >= 1:
length += 1
i *= 10
else:
return length
Testing#
Check if your function returns the expected value using the cell below.
import unittest
class UnitTests(unittest.TestCase):
def test_type(self):
self.assertTrue(isinstance(get_digits(13124), int), 'The function should return an integer.')
def test1(self):
self.assertEqual(get_digits(13124), 5)
def test2(self):
self.assertEqual(get_digits(0), 1)
def test3(self):
self.assertEqual(get_digits(-12381428), 8)
def test4(self):
self.assertEqual(get_digits(12), 2)
def test5(self):
self.assertEqual(get_digits(42), 2)
def test6(self):
self.assertEqual(get_digits(1000), 4)
def test7(self):
self.assertEqual(get_digits(136), 3)
def test8(self):
self.assertEqual(get_digits(1000000000), 10)
def test9(self):
self.assertEqual(get_digits(2147483647), 10)
unittest.main(argv=[''], verbosity=2,exit=False)
test1 (__main__.UnitTests) ...
ok
test2 (__main__.UnitTests) ...
ok
test3 (__main__.UnitTests) ...
ok
test4 (__main__.UnitTests) ...
ok
test5 (__main__.UnitTests) ...
ok
test6 (__main__.UnitTests) ...
ok
test7 (__main__.UnitTests) ...
ok
test8 (__main__.UnitTests) ...
ok
test9 (__main__.UnitTests) ...
ok
test_type (__main__.UnitTests) ...
ok
----------------------------------------------------------------------
Ran 10 tests in 0.005s
OK
<unittest.main.TestProgram at 0x7f2af0a5bfd0>