Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function that count with local var

Tags:

java

recursion

I'm having a question about recursive functions.

I've made this little example program that counts the individual numbers in an integers: example: 123 = 6 because 1 + 2 + 3 = 6.

Now I've made it with a static int and this recursive functions:

  static int totalNumbers(int a)
  { 
    if(a <= 0)
      return sum;
    else
    {
      sum += a % 10;
      return totalNumbers(a/10);
    }
  }

The function works like a charm but my question is, can I make it without a static int called sum? Is there a way that I can define a integer sum in the function and let them count up with a local var or is it not possible?

Kind regards,

like image 557
user1007522 Avatar asked Jun 29 '26 03:06

user1007522


2 Answers

Of course:

static int totalNumbers(int a)
  { 
    if(a <= 0)
      return 0;
    else
    {
      return (a % 10) + totalNumbers(a/10);
    }
  }
like image 172
yurib Avatar answered Jul 01 '26 17:07

yurib


static int totalNumbers(int a)
{
    return a < 10 ? a : (a % 10) + totalNumbers(a / 10);
}
like image 34
fge Avatar answered Jul 01 '26 18:07

fge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!