Leetcode 3079. Find the Sum of Encrypted Integers
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:
d
in the encrypted integers was originally the digit 9 - d
.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.
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
encryptedNums
guaranteed to be positive integers?encryptedNums
: What are the maximum possible values for the length and elements of encryptedNums
?decryptNumber
to decrypt each number based on the rule d = 9 - encryptedDigit
.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
}
}
n
is the number of elements in encryptedNums
and d
is the typical number of digits in each number, the overall complexity is O(n * d).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.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?