recursion - In a Java recursive way, return the diff between 2 numbers digits -


i got quiestion , can't figure out how it,

write recursive function gets 2 positive numbers , return difference between these number digit

for example n1=24646468 , n2=248 returns 5

        public static int diff(int n1, int n2){         int sum1=0;         int sum2=0;         if(n1==0 && n2==0){             return sum1-sum2;         }         if(n1>n2){             if(n2==0){                 sum1++;                 return diff(n1/10, n2);             }             sum2++;             return diff(n1,n2/10);         }         if(n1<n2){             if(n1==0){                 sum2++;                 return diff(n1, n2/10);             }             sum1++;             return diff(n1/10,n2);         }         return 0;     } 

it returns 0

if knows whats wrong code thank :)

the return not recursive call diff returns sum1-sum2 , 2 variables assigned 0 or return 0 @ last line.

you want keep track of state recurse.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -