Description
Minimum Element After Replacement With Digit Sum
EasyYou are given an integer array nums.
You replace each element in nums with the sum of its digits.
Return the minimum element in nums after all replacements.
Example 1:
Input: nums = [10,12,13,14]
Output: 1
Explanation:
nums becomes [1, 3, 4, 5] after all replacements, with minimum element 1.
Example 2:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
nums becomes [1, 2, 3, 4] after all replacements, with minimum element 1.
Example 3:
Input: nums = [999,19,199]
Output: 10
Explanation:
nums becomes [27, 10, 19] after all replacements, with minimum element 10.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 104
Solutions
Iterate through the numbers and calculate the sum of their digits. Keep track of the minimum sum found. Return the minimum sum.
Language: javascript()DONE
CPU Performance100.00%
x
Memory Performance83.91%
x
/**
* @param {number[]} nums
* @return {number}
*/
var minElement = function(nums) {
let min = Infinity;
for (let num of nums) {
let sum = 0;
while (num > 0 && sum < min) {
sum += num % 10;
num = Math.trunc(num / 10);
}
if (sum < min) {
min = sum;
}
}
return min;
};