algoadvance

Leetcode 3079. Find the Sum of Encrypted Integers

Problem Statement

You are given a list of integers. You need to encrypt these integers and then find their sum. The encryption process is defined as follows:

  1. Encryption of each integer:
    • If the integer is positive, reverse its digits.
    • If the integer is negative, reverse its digits (ignoring the sign) and then reapply the negative sign.
  2. Sum of encrypted integers:
    • Compute the sum of all encrypted integers.

Give the result as an integer.

Clarifying Questions

  1. Input Values:
    • What is the range of the integer values we can expect in the input list? (e.g., is there a maximum or minimum value for the integers?)

    Clarification: Assume the input values range between standard 32-bit integer limits (-2^31 to 2^31 - 1).

  2. Input List:
    • Should we assume the input list will always have at least one integer?

    Clarification: Yes, assume the input list is non-empty.

  3. Output Format:
    • Should the output be returned or printed?

    Clarification: The output should be returned.

Strategy

  1. Reverse Digits Function:
    • Create a helper function to reverse the digits of an integer. This function will handle both positive and negative integers.
  2. Iterate Through List:
    • Iterate through the input list, applying the encryption process to each integer.
  3. Sum Encrypted Integers:
    • Sum all the encrypted integers.
  4. Return Result:
    • Return the final sum.

Code

#include <iostream>
#include <vector>
#include <cmath>

class Solution {
public:
    int reverseDigits(int num) {
        int reversedNum = 0;
        int sign = num < 0 ? -1 : 1;
        num = std::abs(num);
        
        while (num > 0) {
            reversedNum = reversedNum * 10 + (num % 10);
            num /= 10;
        }
        
        return reversedNum * sign;
    }

    int sumOfEncryptedIntegers(const std::vector<int>& nums) {
        int sum = 0;
        
        for (int num : nums) {
            sum += reverseDigits(num);
        }
        
        return sum;
    }
};

int main() {
    Solution solution;
    std::vector<int> nums = {123, -456, 789};
    std::cout << "Sum of Encrypted Integers: " << solution.sumOfEncryptedIntegers(nums) << std::endl;
    return 0;
}

Time Complexity

The space complexity is (O(1)) for the reverseDigits process since it uses a fixed amount of extra space regardless of the input size. The overall space complexity is (O(n)) considering the input list.

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