[LeetCode] Find the Sum of Encrypted Integers

3079. Find the Sum of Encrypted Integers

You are given an integer array nums containing positive integers. We define a function encrypt such that encrypt(x) replaces every digit in x with the largest digit in x. For example, encrypt(523) = 555 and encrypt(213) = 333.

Return the sum of encrypted elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int helper(int n) {
int best = 0, cnt = 0;
while(n) {
best = max(best, n % 10);
cnt += 1;
n /= 10;
}
int res = 0;
for(int i = 0; i < cnt; i++) {
res += best;
best *= 10;
}
return res;
}
public:
int sumOfEncryptedInt(vector<int>& nums) {
int res = 0;
for(auto& n : nums) res += helper(n);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/17/PS/LeetCode/find-the-sum-of-encrypted-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.