简体   繁体   中英

Count Total Digits in a Number useing recursion and when n is 0 then count it's and print 1 . and my question is how to count 0 as digits and print 1?

public class CountNumberRecursion 
{
    
    public static int countDigits(int n)
    {
        int count=0;
        
        if(n==0)
            return n;
        
        return ++count + countDigits(n/10);
    }

    public static void main(String[] args) 
    {
         System.out.println(countDigits(0));
    }

}

In this example run, I want to count 0 as digits and print 1 in output, but it prints 0.

This is an understandable issue. On the one hand we have the case where a single digit is passed as n , and then the recursive call for n/10 should return 0 (as it does now).

On the other hand, if the value n is 0 from the start , it should return 1.

This is a contradiction that you can solve by making 0 a special case in the main program. But this is solved more elegantly by stopping the recursion one step earlier , so not when all digits are gone, but when there is one digit. This you can implement by changing:

if(n==0)
    return n;

...to:

if(n<10)  // Only 1 digit?
    return 1;

This way the function can never return 0, so even for 0 it will return 1.

Remark

It is bit overkill to have the count variable. You can just add 1 to what the recursive call returns:

return 1 + countDigits(n/10);

With a conditional operator, both the base case and the recursive case can be combined in one expression:

public static int countDigits(int n)
{
    return n < 10 ? 1 : 1 + countDigits(n/10);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM