Posts

Showing posts with the label Javascript

Count Total Digits in a Number in Javascript using recursion

 In this article we will use recursion to count total digits in a given number function countDigits(n){ if (n == 0 ){ return n; } return 1 + countDigits( parseInt (n/ 10 )); } let sum= countDigits( 999999 ); console.log( "result" + sum); How this works This is  how countDigits function is called 1 + countDigits(99999) returns 1 +4 = 5      1 + countDigits(9999) returns 1 +3 = 4           1 + countDigits(999) returns 1 +2 = 3                1 + countDigits(99) returns 1 +1 = 2                     1 + countDigits(9) returns 1 +0 = 1                          (n == 0 ) returns 0 First function keeps calling by passing argument then function keeps returning and at last will return the final result.

Sum of digits using Recursion in Javascript.

 Recursion in Javascript function sumOfDigits(n){ let num = parseInt(n/ 10 ); let digit = n% 10 ; if (n == 0 ){ return n; } return digit + sumOfDigits(num); } let sum= sumOfDigits( 99999 ); console. log ( "result" + sum); How this works 9 + sumOfDigits(9999) = returns 9 + 36 = 45      9 + sumOfDigits(999) = returns 9 + 27 = 36                9 + sumOfDigits(99) = returns 9 + 18 = 27                          9 + sumOfDigits(9) = returns 9 + 9 = 18                               9 + sumOfDigits(0) = returns 9 So finally it returns 45, which is the sum of digits.