Find the average of k digits from the beginning and l digits from the end of the given number

Given three integers N, K and L. The task is to find the average of the first K digits and the last L digits of the given number N without any digit overlapping.
Examples:Â
Â
Input: N = 123456, K = 2, L = 3Â
Output: 3.0Â
Sum of first K digits will be 1 + 2 = 3Â
Sum of last L digits will be 4 + 5 + 6 = 15Â
Average = (3 + 15) / (2 + 3) = 18 / 5 = 3
Input: N = 456966, K = 1, L = 1Â
Output: 5.0Â
Â
Â
Approach: If the count of digits in n is less than (K + L) then it isn’t possible to find the average without digits overlapping and print -1 in that case. If that’s not the case, find the sum of the last L digits of N and store it in a variable say sum1 then find the sum of the first K digits of N and store it in sum2. Now, print the average as (sum1 + sum2) / (K + L).
Below is the implementation of the above approach:Â
Â
C++
// implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the count// of digits in numint countDigits(int num){Â Â Â Â int cnt = 0;Â Â Â Â while (num > 0) Â Â Â Â {Â Â Â Â Â Â Â Â cnt++;Â Â Â Â Â Â Â Â num /= 10;Â Â Â Â }Â Â Â Â return cnt;}Â
// Function to return the sum// of first n digits of numint sumFromStart(int num, int n, int rem){Â
    // Remove the unnecessary digits    num /= ((int)pow(10, rem));Â
    int sum = 0;    while (num > 0)    {        sum += (num % 10);        num /= 10;    }    return sum;}Â
// Function to return the sum// of the last n digits of numint 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){Â
    // If the average can't be calculated without    // using the same digit more than once    int totalDigits = countDigits(n);    if (totalDigits < (k + l))        return -1;Â
    // Sum of the last l digits of n    int sum1 = sumFromEnd(n, l);Â
    // 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    int sum2 = sumFromStart(n, k, totalDigits - k);Â
    // Return the average    return ((float)(sum1 + sum2) /             (float)(k + l));}Â
// Driver codeint main(){Â Â Â Â int n = 123456, k = 2, l = 3;Â Â Â Â cout << getAverage(n, k, l);Â
    return 0;}Â
// This code is contributed by PrinciRaj1992 |
Java
// Java implementation of the approachclass GFG {Â
    // Function to return the count    // of digits in num    public static int countDigits(int num)    {        int cnt = 0;        while (num > 0) {            cnt++;            num /= 10;        }        return cnt;    }Â
    // Function to return the sum    // of first n digits of num    public static int sumFromStart(int num, int n, int rem)    {Â
        // Remove the unnecessary digits        num /= ((int)Math.pow(10, rem));Â
        int sum = 0;        while (num > 0) {            sum += (num % 10);            num /= 10;        }        return sum;    }Â
    // Function to return the sum    // of the last n digits of num    public static int sumFromEnd(int num, int n)    {        int sum = 0;        for (int i = 0; i < n; i++) {            sum += (num % 10);            num /= 10;        }        return sum;    }Â
    public static float getAverage(int n, int k, int l)    {Â
        // If the average can't be calculated without        // using the same digit more than once        int totalDigits = countDigits(n);        if (totalDigits < (k + l))            return -1;Â
        // Sum of the last l digits of n        int sum1 = sumFromEnd(n, l);Â
        // 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        int sum2 = sumFromStart(n, k, totalDigits - k);Â
        // Return the average        return ((float)(sum1 + sum2) / (float)(k + l));    }Â
    // Driver code    public static void main(String args[])    {        int n = 123456, k = 2, l = 3;        System.out.print(getAverage(n, k, l));    }} |
Python3
# implementation of the approachfrom math import powÂ
# Function to return the count# of digits in numdef countDigits(num):Â Â Â Â cnt = 0Â Â Â Â while (num > 0):Â Â Â Â Â Â Â Â cnt += 1Â Â Â Â Â Â Â Â num //= 10Â Â Â Â return cntÂ
# Function to return the sum# of first n digits of numdef sumFromStart(num, n, rem):         # Remove the unnecessary digits    num //= pow(10, rem)Â
    sum = 0    while (num > 0):        sum += (num % 10)        num //= 10    return sumÂ
# Function to return the sum# of the last n digits of numdef sumFromEnd(num, n):Â Â Â Â sum = 0Â Â Â Â for i in range(n):Â Â Â Â Â Â Â Â sum += (num % 10)Â Â Â Â Â Â Â Â num //= 10Â Â Â Â Â Â Â Â Â return sumÂ
def getAverage(n, k, l):         # If the average can't be calculated without    # using the same digit more than once    totalDigits = countDigits(n)    if (totalDigits < (k + l)):        return -1Â
    # Sum of the last l digits of n    sum1 = sumFromEnd(n, l)Â
    # 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    sum2 = sumFromStart(n, k, totalDigits - k)Â
    # Return the average    return (sum1 + sum2) / (k + l)Â
# Driver codeif __name__ == '__main__':Â Â Â Â n = 123456Â Â Â Â k = 2Â Â Â Â l = 3Â Â Â Â print(getAverage(n, k, l))Â
# This code is contributed by# Surendra_Gangwar |
C#
// C# implementation of the approach using System;Â
class GFG { Â
    // Function to return the count     // of digits in num     public static int countDigits(int num)     {         int cnt = 0;         while (num > 0)         {             cnt++;             num /= 10;         }         return cnt;     } Â
    // Function to return the sum     // of first n digits of num     public static int sumFromStart(int num,                                   int n, int rem)     { Â
        // Remove the unnecessary digits         num /= ((int)Math.Pow(10, rem)); Â
        int sum = 0;         while (num > 0)         {             sum += (num % 10);             num /= 10;         }         return sum;     } Â
    // Function to return the sum     // of the last n digits of num     public static int sumFromEnd(int num, int n)     {         int sum = 0;         for (int i = 0; i < n; i++)        {             sum += (num % 10);             num /= 10;         }         return sum;     } Â
    public static float getAverage(int n, int k, int l)     { Â
        // If the average can't be calculated without         // using the same digit more than once         int totalDigits = countDigits(n);         if (totalDigits < (k + l))             return -1; Â
        // Sum of the last l digits of n         int sum1 = sumFromEnd(n, l); Â
        // 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         int sum2 = sumFromStart(n, k, totalDigits - k); Â
        // Return the average         return ((float)(sum1 + sum2) /                 (float)(k + l));     } Â
    // Driver code     public static void Main(String []args)     {         int n = 123456, k = 2, l = 3;         Console.WriteLine(getAverage(n, k, l));     } } Â
// This code is contributed by Princi Singh |
Javascript
<script>// javascript implementation of the approach   Â
    // Function to return the count    // of digits in num    function countDigits(num)    {        var cnt = 0;        while (num > 0)        {            cnt++;            num = parseInt(num/10);        }        return cnt;    }Â
    // Function to return the sum    // of first n digits of num    function sumFromStart(num, n, rem)    {Â
        // Remove the unnecessary digits        num = (parseInt( num/Math.pow(10, rem)));Â
        var sum = 0;        while (num > 0)         {            sum += (num % 10);            num = parseInt(num/10);        }        return sum;    }Â
    // Function to return the sum    // of the last n digits of num    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) {Â
        // If the average can't be calculated without        // using the same digit more than once        var totalDigits = countDigits(n);        if (totalDigits < (k + l))            return -1;Â
        // Sum of the last l digits of n        var sum1 = sumFromEnd(n, l);Â
        // 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        var sum2 = sumFromStart(n, k, totalDigits - k);Â
        // Return the average        return ( (sum1 + sum2) / (k + l));    }Â
    // Driver code    var n = 123456, k = 2, l = 3;    document.write(getAverage(n, k, l));Â
// This code is contributed by Rajput-Ji</script> |
3.6
Using string slicing and sum() function:
Approach:
This approach involves converting the given number into a string and then using string slicing to extract the required digits. The sum() function is used to calculate the sum of the extracted digits, and the average is calculated by dividing the sum by the total number of digits.
Convert the given number N to a string.
Take the first K digits of the string (from the beginning) and the last L digits of the string (from the end).
Concatenate the first K digits and the last L digits into a single string.
Convert the concatenated string of digits to a list of integers.
Calculate the sum of the integers in the list.
Calculate the average of the sum of digits from step 5 and divide by the sum of K and L.
Return the average as the result.
C++
// c++ program implementation#include <iostream>#include <string>Â
using namespace std;Â
double average_of_digits_1(int N, int K, int L) {Â Â Â Â string digits = to_string(N);Â Â Â Â string first_k = digits.substr(0, K);Â Â Â Â string last_l = digits.substr(digits.size()-L);Â Â Â Â int sum_of_digits = 0;Â Â Â Â for (char c : first_k + last_l) {Â Â Â Â Â Â Â Â sum_of_digits += (c - '0');Â Â Â Â }Â Â Â Â double average = static_cast<double>(sum_of_digits) / (K + L);Â Â Â Â return average;}Â
int main() {Â Â Â Â int N = 123456;Â Â Â Â int K = 2;Â Â Â Â int L = 3;Â Â Â Â cout << "Input: N = " << N << " K = " << K << " L = " << L << endl;Â Â Â Â cout << "Output: " << average_of_digits_1(N, K, L) << endl;Â
    N = 456966;    K = 1;    L = 1;    cout << "Input: N = " << N << " K = " << K << " L = " << L << endl;    cout << "Output: " << average_of_digits_1(N, K, L) << endl;Â
    return 0;} |
Java
public class AverageOfDigits {Â Â Â Â public static double averageOfDigits(int N, int K, int L) {Â Â Â Â Â Â Â Â String digits = String.valueOf(N);Â Â Â Â Â Â Â Â String firstK = digits.substring(0, K);Â Â Â Â Â Â Â Â String lastL = digits.substring(digits.length() - L);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int sumOfDigits = 0;Â Â Â Â Â Â Â Â for (char c : (firstK + lastL).toCharArray()) {Â Â Â Â Â Â Â Â Â Â Â Â sumOfDigits += (c - '0');Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â double average = (double) sumOfDigits / (K + L);Â Â Â Â Â Â Â Â return average;Â Â Â Â }Â
    public static void main(String[] args) {        int N = 123456;        int K = 2;        int L = 3;        System.out.println("Input: N = " + N + " K = " + K + " L = " + L);        System.out.println("Output: " + averageOfDigits(N, K, L));Â
        N = 456966;        K = 1;        L = 1;        System.out.println("Input: N = " + N + " K = " + K + " L = " + L);        System.out.println("Output: " + averageOfDigits(N, K, L));    }} |
Python3
def average_of_digits_1(N, K, L):Â Â Â Â digits = str(N)Â Â Â Â first_k = digits[:K]Â Â Â Â last_l = digits[-L:]Â Â Â Â sum_of_digits = sum(map(int, first_k + last_l))Â Â Â Â average = sum_of_digits / (K + L)Â Â Â Â return averageÂ
# Example usageN = 123456K = 2L = 3print("Input: N =", N, "K =", K, "L =", L)print("Output:", average_of_digits_1(N, K, L))Â
N = 456966K = 1L = 1print("Input: N =", N, "K =", K, "L =", L)print("Output:", average_of_digits_1(N, K, L)) |
C#
using System;Â
class Program {    // Function to calculate the average of digits in a    // number    static double AverageOfDigits(int N, int K, int L)    {        // Convert the number to a string to work with its        // digits        string digits = N.ToString();Â
        // Extract the first K and last L digits        string firstK = digits.Substring(0, K);        string lastL = digits.Substring(digits.Length - L);Â
        int sumOfDigits = 0;Â
        // Calculate the sum of digits in the selected        // portion        foreach(char c in firstK + lastL)        {            sumOfDigits                += (c                    - '0'); // Convert character to integer        }Â
        // Calculate and return the average        double average = (double)sumOfDigits / (K + L);        return average;    }Â
    static void Main(string[] args)    {        int N = 123456;        int K = 2;        int L = 3;Â
        Console.WriteLine("Input: N = " + N + " K = " + K                          + " L = " + L);        Console.WriteLine("Output: "                          + AverageOfDigits(N, K, L));Â
        N = 456966;        K = 1;        L = 1;Â
        Console.WriteLine("Input: N = " + N + " K = " + K                          + " L = " + L);        Console.WriteLine("Output: "                          + AverageOfDigits(N, K, L));    }} |
Input: N = 123456 K = 2 L = 3 Output: 3.6 Input: N = 456966 K = 1 L = 1 Output: 5.0
Time complexity: O(K+L)
Auxiliary Space: O(K+L)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



