2

I've been trying to find how do I do check the length of integer using recursion. For example: 100, it will say that there's 3 number. 12, it will say that there's 2 number.

What I've saw online is all about the summation of the last digit. I couldn't source for help on the length of an integer.

can someone help me out on this? I've tried to use lens to count, but my output is always 0.

def num(x):
   if x == 0:
       return 0
   else:
       return num(x / 10)
print len(str(num(100)))

I've also tried this

def num(x):
       if x == 0:
           return 0
       else:
           return num(x / 10) + len(str(x % 10))
    print num(100)

2 Answers 2

1

You need to add 1 with num(N/10) if N is not 0 :

>>> def num(N):
...   if N==0:
...      return 0
...   return 1+num(N/10)
... 
>>> num(100)
3

This code will add ones in each calling the function with N/10 until it get to 0, so at the end based on what time your number can bi divide by 10 you'll have 1's which have been sum together, and at last for 0 they eill be add with 0.

For example for 100 your function will do the following :

1+(100/10)
      ^
1+1+(10/10)
       ^
 1+1+1(1/10)
        ^
  1+1+1+0
Sign up to request clarification or add additional context in comments.

7 Comments

Hi, Can you explain to me why is there a 1+ needed?
meaning,if let say I've this number (12345) n/10 will basically check it will loop how many time, right? & each time when it check, it will + 1, thus the output will be 5. Am I right to say that?
@stack Exactly! for better demonstration check the edit again ;)
thank you so much. Do you know if I will to use a while loop in it, how it should be?
@stack Welcome, that would be a simple task you can just try it by your self! ;) as a hint you need to add ones till N gets to 0.
|
1

Are you looking for this -

def numlen(i):
    if i:
        return numlen(i//10) + 1
    return 0

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.