164,074 views
20 votes
20 votes
Write a recursive function called DigitCount() that takes a positive integer as a parameter and returns the number of digits in the integer. Hint: The number of digits increases by 1 whenever the input number is divided by 10. Ex: If the input is:

User Russt
by
2.4k points

2 Answers

26 votes
26 votes

Final answer:

To write a recursive function called DigitCount() that takes a positive integer as a parameter and returns the number of digits in the integer, you can define a base case where if the integer is less than 10, the function returns 1.

Step-by-step explanation:

To write a recursive function called DigitCount() that takes a positive integer as a parameter and returns the number of digits in the integer, you can define a base case where if the integer is less than 10, the function returns 1. Otherwise, the function calls itself with the integer divided by 10 and adds 1 to the result. Here's an example in Python:

def DigitCount(n):
if n < 10:
return 1
else:
return 1 + DigitCount(n // 10)

For example, if you call DigitCount(12345), the function will recursively divide the number by 10 until it reaches the base case, resulting in the number of digits being returned as 5.

User Soloidx
by
2.8k points
19 votes
19 votes

Final answer:

The DigitCount() function is a recursive method to calculate the number of digits in a positive integer by repeatedly dividing by 10 until the number is less than 10 and counting each division as a single digit.

Step-by-step explanation:

The DigitCount() function is a recursive function designed to count the number of digits in a positive integer. The function works by repeatedly dividing the input number by 10, a process tied to the powers-of-ten notation of our number system.

Since each place in our decimal number system is based on increases of ten, a single digit occupies each power of ten place, progressing from right to left. The process of recursion continues until the number is reduced to a value less than 10, which is the base case of the recursion, indicating a single digit remains.

To define the function in a programming language like Python:

def DigitCount(n):
if n < 10:
return 1
else:
return 1 + DigitCount(n // 10)

This code checks if the number n is less than 10. If so, it returns 1. Otherwise, the function calls itself with the floor division of n by 10, effectively peeling off the last digit of the number and counting the number of such operations as it recurses back up.

User Waldo Hampton
by
3.2k points