We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Sum of Encrypted Integers

Number: 3367

Difficulty: Easy

Paid? No

Companies: Larsen & Toubro


Problem Description

You are given an array of positive integers. For each integer, we define an encryption function that replaces every digit with the largest digit present in that integer. The task is to compute the sum of all these encrypted numbers.


Key Insights

  • For each number, determine its maximum digit.
  • Replace every digit of the number with this maximum digit.
  • The encrypted number can be reconstructed by repeating the maximum digit for the number of digits found in the original number.
  • Sum up all the encrypted numbers.
  • Since the constraints are small, simple string manipulation and arithmetic suffice.

Space and Time Complexity

Time Complexity: O(n * d), where n is the number of elements in nums and d is the number of digits in a number (at most 4 given nums[i] ≤ 1000). Space Complexity: O(1) extra space, aside from the space required for the input.


Solution

For each number in the array, first convert it into a string to easily iterate over its digits. Find the maximum digit. Then, compute the encrypted number by forming a new number where every position is filled with this maximum digit. This can either be done by string repetition and conversion to integer or by mathematical computation using the formula: newNumber = maxDigit repeated d times = maxDigit * ((10^d - 1) / 9). Finally, sum all the encrypted numbers and return the result.


Code Solutions

# Function to find the sum of encrypted integers
def sum_encrypted_numbers(nums):
    total_sum = 0
    # Iterate through each number in the list
    for num in nums:
        num_str = str(num)              # Convert number to string to iterate digits
        max_digit = max(num_str)          # Find the maximum digit (as a character)
        # The encrypted number is created by repeating max_digit for len(num_str) times
        encrypted_num = int(max_digit * len(num_str))
        total_sum += encrypted_num       # Add the encrypted number to the total sum
    return total_sum

# Example usage:
nums = [10, 21, 31]
print(sum_encrypted_numbers(nums))    # Expected Output: 66
← Back to All Questions