0

Needs to return the number of digits in an integer using recursion.NO LOOPS and cannot use str function either.I have the general case but i need help with the base case:

    def count(x):
       x=abs(x)
      #general case
      if x<10:
       return 1
      #base case 

    x=123
    print(count(x))
2
  • Are you passing an int to the function or a string. cause currently your passing a string so can just return len(x) Commented Nov 27, 2019 at 20:01
  • sorry about that,that was a mistake i just edited it Commented Nov 27, 2019 at 20:04

1 Answer 1

1

you are on the right track, so when its less than 10 you know that its a single digit so you can return 1, otherwise its greater than 10 so return 1 + the result of the function passing in x // 10

def count(x):
    if abs(x) > 10:
        return 1 + count(x // 10)
    return 1


for i in (1, 23, 345, 454564, 34, -345, -98):
    print(f'There are {count(i)} digits in the number {i}')

OUTPUT

There are 1 digits in the number 1
There are 2 digits in the number 23
There are 3 digits in the number 345
There are 6 digits in the number 454564
There are 2 digits in the number 34
There are 3 digits in the number -345
There are 2 digits in the number -98
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.