Sum of Digits in the Minimum Number
Problem
Given an integer array nums, find the smallest value among its elements. Let S be the sum of the digits of that minimum value. Return 0 if S is odd, or 1 if S is even.
nums = [34, 23, 1, 24, 75, 33, 54, 8]0def sum_of_digits(nums):
m = min(nums)
s = 0
while m > 0:
s += m % 10
m //= 10
return 1 - s % 2
function sumOfDigits(nums) {
let m = Math.min(...nums);
let s = 0;
while (m > 0) {
s += m % 10;
m = Math.floor(m / 10);
}
return 1 - (s % 2);
}
class Solution {
public int sumOfDigits(int[] nums) {
int m = nums[0];
for (int x : nums) m = Math.min(m, x);
int s = 0;
while (m > 0) {
s += m % 10;
m /= 10;
}
return 1 - s % 2;
}
}
int sumOfDigits(vector<int>& nums) {
int m = *min_element(nums.begin(), nums.end());
int s = 0;
while (m > 0) {
s += m % 10;
m /= 10;
}
return 1 - s % 2;
}
Explanation
This problem is really three tiny steps glued together: find the smallest number, add up its digits, then look at whether that total is even or odd.
First we grab the minimum with min(nums). Then we peel off its digits one at a time: m % 10 gives the last digit, and m //= 10 chops it off. We keep adding those digits into s until m becomes 0.
The clever finish is return 1 - s % 2. Here s % 2 is 1 when the sum is odd and 0 when it is even, so 1 - s % 2 flips that into the required answer: 0 for odd, 1 for even.
Example: nums = [34, 23, 1, 24, 75, 33, 54, 8]. The minimum is 1, its digit sum is 1, which is odd, so s % 2 = 1 and the answer is 1 - 1 = 0.
It works because we only ever care about the one smallest value, and a single pass over its digits is enough to decide the parity.