Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 num
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
int 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 num
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)
{
 
    // 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
int 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 approach
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;
        System.out.print(getAverage(n, k, l));
    }
}


Python3




# implementation of the approach
from math import pow
 
# Function to return the count
# of digits in num
def countDigits(num):
    cnt = 0
    while (num > 0):
        cnt += 1
        num //= 10
    return cnt
 
# Function to return the sum
# of first n digits of num
def 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 num
def 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 code
if __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>


Output

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 usage
N = 123456
K = 2
L = 3
print("Input: N =", N, "K =", K, "L =", L)
print("Output:", average_of_digits_1(N, K, L))
 
N = 456966
K = 1
L = 1
print("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));
    }
}


Javascript




// Function to calculate the average of K digits from the beginning and L digits from the end of N
function averageOfDigits(N, K, L) {
    // Convert N to a string to work with its digits
    const digits = N.toString();
     
    // Extract the first K digits and the last L digits
    const firstK = digits.slice(0, K);
    const lastL = digits.slice(-L);
     
    // Calculate the sum of the extracted digits
    let sumOfDigits = 0;
    for (let i = 0; i < firstK.length; i++) {
        sumOfDigits += parseInt(firstK[i]);
    }
    for (let i = 0; i < lastL.length; i++) {
        sumOfDigits += parseInt(lastL[i]);
    }
     
    // Calculate the average
    const average = sumOfDigits / (K + L);
    return average;
}
 
// Test cases
let N = 123456;
let K = 2;
let L = 3;
console.log("Input: N =", N, "K =", K, "L =", L);
console.log("Output:", averageOfDigits(N, K, L));
 
N = 456966;
K = 1;
L = 1;
console.log("Input: N =", N, "K =", K, "L =", L);
console.log("Output:", averageOfDigits(N, K, L));


Output

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)



Last Updated : 12 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads