Find the average of k digits from the beginning and l digits from the end of the given number | implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigits ( int num ) { int cnt = 0 ; while ( num > 0 ) { cnt ++ ; num /= 10 ; } return cnt ; } int sumFromStart ( int num , int n , int rem ) { num /= ( ( int ) pow ( 10 , rem ) ) ; int sum = 0 ; while ( num > 0 ) { sum += ( num % 10 ) ; num /= 10 ; } return sum ; } int sumFromEnd ( int num , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += ( num % 10 ) ; num /= 10 ; } return sum ; } float getAverage ( int n , int k , int l ) { int totalDigits = countDigits ( n ) ; if ( totalDigits < ( k + l ) ) return -1 ; int sum1 = sumFromEnd ( n , l ) ; int sum2 = sumFromStart ( n , k , totalDigits - k ) ; return ( ( float ) ( sum1 + sum2 ) / ( float ) ( k + l ) ) ; } int main ( ) { int n = 123456 , k = 2 , l = 3 ; cout << getAverage ( n , k , l ) ; return 0 ; }