Code Examples

Count digits in number

programming

The following code in Python counts digits in a given number.

# this function returns number of digits
# in a given integer
def digits(n):
    count = 0

    if n == 0:
        return 1
    while (n >= 1):
        count += 1
        n = n/10
    return count

# test cases
print(digits(25))   # should print 2
print(digits(144))  # should print 3
print(digits(1000)) # should print 4
print(digits(0))    # should print 1