java - Solving Recursion -


why return 9 plus actual value of answer. example, number 1234, answer 1 yet function returns 10. don't know why case, i'm pretty sure recursion have no idea.

int fun(int n) {     if (n <= 9) {         return n;     } else {         return fun(n / 10) + (n % 10);     } } 

as makoto stated, it's unclear why believe answer should 1. however, if recursion analysis following:

fn(1234) = fn(123) + 4 = 10 fn(123)  = fn(12) + 3  = 6 fn(12)   = fn(1) + 2   = 3 fn(1)    = 1 

therefore, using simple substitution, get:

fn(1234) = 1 + 2 + 3 + 4 = 10 

Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -