class Solution:
def sumOfDigits(self, nums):
min_num = min(nums)
return sum(int(d) for d in str(abs(min_num)))
class Solution {
public:
int sumOfDigits(vector<int>& nums) {
int minNum = *min_element(nums.begin(), nums.end());
int sum = 0;
minNum = abs(minNum);
while (minNum) {
sum += minNum % 10;
minNum /= 10;
}
return sum;
}
};
class Solution {
public int sumOfDigits(int[] nums) {
int minNum = Integer.MAX_VALUE;
for (int n : nums) {
minNum = Math.min(minNum, Math.abs(n));
}
int sum = 0;
minNum = Math.abs(minNum);
while (minNum > 0) {
sum += minNum % 10;
minNum /= 10;
}
return sum;
}
}
var sumOfDigits = function(nums) {
let minNum = Math.min(...nums.map(Math.abs));
let sum = 0;
minNum = Math.abs(minNum);
while (minNum > 0) {
sum += minNum % 10;
minNum = Math.floor(minNum / 10);
}
return sum;
};
You are given an array of integers called nums
. The task is to find the minimum number in the array, and then return the sum of its digits. If the minimum number is negative, consider its absolute value when summing the digits.
nums
of integers (may include negatives).nums
.To solve this problem, first, we need to identify the smallest number in the array. Once we have it, we need to compute the sum of its digits. If the number is negative, we should ignore the sign and sum the digits of its absolute value.
The brute-force approach would be to:
The key insight is that finding a minimum in an array and summing digits are both straightforward operations, so the problem is not about complex data structures but about careful handling of negatives and digit extraction.
nums
array and keep track of the smallest value found.min()
for Python or Math.min()
for JavaScript/Java.This approach is efficient and easy to implement in any programming language, as shown in the code section.
Consider the input nums = [34, 23, 1, 24, 75, 33, 54, 8]
.
1
.abs(1) = 1
1
1
as the result.
Let's try another input: nums = [-15, -2, -30, 7]
.
-30
.30
.3 + 0 = 3
.3
as the result.nums
.Thus, the solution is efficient for large arrays.
The "Sum of Digits in the Minimum Number" problem is straightforward: find the smallest number in the array, take its absolute value, and sum its digits. The main insight is to handle negatives correctly and efficiently sum digits. The solution is elegant because it leverages simple array traversal and digit extraction, resulting in clear, fast, and memory-efficient code.