Find the average of k digits from the beginning and l digits from the end of the given number | Function to return the count of digits in num ; Function to return the sum of first n digits of num ; Remove the unnecessary digits ; Function to return the sum of the last n digits of num ; If the average can 't be calculated without  using the same digit more than once ; Sum of the last l digits of n ; Sum of the first k digits of n ( totalDigits - k ) must be removed from the end of the number to get the remaining k digits from the beginning ; Return the average ; Driver code
function countDigits ( num ) { var cnt = 0 ; while ( num > 0 ) { cnt ++ ; num = parseInt ( num / 10 ) ; } return cnt ; } function sumFromStart ( num , n , rem ) { num = ( parseInt ( num / Math . pow ( 10 , rem ) ) ) ; var sum = 0 ; while ( num > 0 ) { sum += ( num % 10 ) ; num = parseInt ( num / 10 ) ; } return sum ; } function sumFromEnd ( num , n ) { var sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { sum += ( num % 10 ) ; num = parseInt ( num / 10 ) ; } return sum ; } function getAverage ( n , k , l ) { var totalDigits = countDigits ( n ) ; if ( totalDigits < ( k + l ) ) return - 1 ; var sum1 = sumFromEnd ( n , l ) ; var sum2 = sumFromStart ( n , k , totalDigits - k ) ; return ( ( sum1 + sum2 ) / ( k + l ) ) ; } var n = 123456 , k = 2 , l = 3 ; document . write ( getAverage ( n , k , l ) ) ;