求出加密整数的和
难度:
标签:
题目描述
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.
Example 1:
Input: nums = [1,2,3]
Output: 6
Explanation: The encrypted elements are [1,2,3]
. The sum of encrypted elements is 1 + 2 + 3 == 6
.
Example 2:
Input: nums = [10,21,31]
Output: 66
Explanation: The encrypted elements are [11,22,33]
. The sum of encrypted elements is 11 + 22 + 33 == 66
.
Constraints:
1 <= nums.length <= 50
1 <= nums[i] <= 1000
代码结果
运行时间: 27 ms, 内存: 16.1 MB
/*
题目思路:
1. 使用Java Stream处理数组。
2. 对于每个整数,找到其最大的数位并用它替换所有数位。
3. 使用map和sum来计算加密后的总和。
*/
import java.util.Arrays;
public class EncryptSumStream {
public static int encrypt(int[] nums) {
return Arrays.stream(nums)
.map(num -> {
int maxDigit = String.valueOf(num).chars()
.map(Character::getNumericValue)
.max()
.orElse(0);
String encryptedStr = String.valueOf(maxDigit).repeat(String.valueOf(num).length());
return Integer.parseInt(encryptedStr);
})
.sum();
}
public static void main(String[] args) {
int[] nums = {10, 21, 31};
System.out.println(encrypt(nums)); // 输出 66
}
}
解释
方法:
这道题目的解法是通过定义一个加密函数`en`,该函数接收一个整数`x`,将其转换为字符串`xx`,然后找出`xx`中的最大数字`xxx`,并用`xxx`替换`xx`中的每个数字,最后将得到的字符串`xxxx`转换回整数并返回。解法的主体部分是对输入数组`nums`中的每个元素应用`en`函数,并将结果相加返回。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在定义加密函数`en`时,为什么选择将整数转换为字符串来处理而不是直接进行数学运算?
▷🦆
函数`en`中使用`max(xx)`来找最大数字,这种方法是否在所有情况下都有效,比如数字开头是0的情况?
▷🦆
在`en`函数中,你是如何确定将整个字符串的每个字符替换为最大值后再转换回整数不会超出整数范围?
▷