algoadvance

Leetcode 3079. Find the Sum of Encrypted Integers

Problem Statement

You are given an array encryptedNums which represents a series of integers that have been encrypted. Your task is to decrypt these integers and calculate their sum. The encryption rule is as follows:

For example, the integer 284 was originally 715 before encryption (2 -> 7, 8 -> 1, 4 -> 5).

Write a function findSumOfDecryptedNums that takes in the array encryptedNums and returns the sum of the decrypted integers.

Examples

Input: encryptedNums = [284, 619]
Output: 1334

Explanation:
- Decrypting 284: 7(9-2), 1(9-8), 5(9-4) -> 715
- Decrypting 619: 3(9-6), 8(9-1), 0(9-9) -> 380
- Sum is 715 + 380 = 1095

Clarifying Questions

  1. Input Format: Are encryptedNums guaranteed to be positive integers?
  2. Output Format: Should the output be a single integer (the sum of decrypted integers)?
  3. Constraints on the size of encryptedNums: What are the maximum possible values for the length and elements of encryptedNums?
  4. Leading Zeros: How should leading zeros after decryption be handled?

Strategy

  1. Decrypt Each Number: We will create a helper function decryptNumber to decrypt each number based on the rule d = 9 - encryptedDigit.
  2. Sum Decrypted Numbers: Sum all the decrypted numbers and return the result.

Code

public class SumOfEncryptedIntegers {

    public static int findSumOfDecryptedNums(int[] encryptedNums) {
        int sum = 0;
        for (int encryptedNum : encryptedNums) {
            sum += decryptNumber(encryptedNum);
        }
        return sum;
    }

    private static int decryptNumber(int encryptedNum) {
        int decryptedNum = 0;
        int placeValue = 1;
        
        while (encryptedNum > 0) {
            int digit = encryptedNum % 10;
            int decryptedDigit = 9 - digit;
            
            decryptedNum += decryptedDigit * placeValue;
            placeValue *= 10;
            
            encryptedNum /= 10;
        }
        
        return decryptedNum;
    }

    public static void main(String[] args) {
        int[] encryptedNums = {284, 619};
        System.out.println(findSumOfDecryptedNums(encryptedNums));  // Output: 1095
    }
}

Time Complexity

This solution efficiently decrypts each number and sums them up in linear time relative to the size of the input and the size of the numbers.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI