Similar Problems

Similar Problems not available

Find The K Beauty Of A Number - Leetcode Solution

Companies:

LeetCode:  Find The K Beauty Of A Number Leetcode Solution

Difficulty: Easy

Topics: math sliding-window string  

Problem Statement:

Given an integer number N and a positive integer K, you are asked to find the K beauty of N. The K beauty of a positive integer N is defined as the sum of k largest digits in the decimal representation of N.

For example, if N = 5321234 and K = 3, then 3 largest digits are 5, 3, and 4, so the 3rd beauty of 5321234 is 5+3+4=12.

Write a function in python to solve this problem.

Solution:

To solve this problem, we first need to find the decimal representation of the given number. We can do this by converting the integer to a string, and then iterating over each character in the string to get the digits.

Next, we need to sort the digits in decreasing order and sum up the first K digits to get the K beauty.

The below python function implements this approach:

def k_beauty(N: int, K: int) -> int:
    # Convert the integer to a string
    str_N = str(N)
    digits = []
    # Iterate over each character in the string to get the digits
    for i in range(len(str_N)):
        digits.append(int(str_N[i]))
    # Sort the digits in decreasing order
    digits.sort(reverse=True)
    # Sum up the first K digits to get the K beauty
    k_beauty = 0
    for i in range(K):
        k_beauty += digits[i]
    return k_beauty

We can test this function with the given example:

N = 5321234
K = 3
print(k_beauty(N, K))

Output:

12

The function correctly calculates the K beauty of the given number N.

Find The K Beauty Of A Number Solution Code

1