Sum of Digits in the Minimum Number Problem
#1085
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1085.
Given an integer array nums, return 0 if the sum of the digits of the minimum integer in nums is odd, or 1 otherwise.
Example 1:
Input: nums = [34,23,1,24,75,33,54,8]
Output: 0
Explanation: The minimal element is 1, and the sum of those digits is 1 which is odd, so the answer is 0.
Example 2:
Input: nums = [99,77,33,66,55]
Output: 1
Explanation: The minimal element is 33, and the sum of those digits is 3 + 3 = 6 which is even, so the answer is 1.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Approach: Find the Minimum, then Add Its Digits
Find the smallest number in nums. Add up its digits by repeatedly taking the last digit with x % 10 and dropping it with x / 10 (integer division). Return 1 when the digit sum is even and 0 when it is odd. Note that this is the opposite of what the parity bit gives (digitSum % 2 is 1 for odd sums).
Complexity: O(n) time to find the minimum, plus O(1) for its digits (at most three, since nums[i] <= 100). O(1) space.
class Solution:
def sumOfDigits(self, nums: List[int]) -> int:
x = min(nums)
digit_sum = 0
while x > 0:
digit_sum += x % 10
x //= 10
return 1 if digit_sum % 2 == 0 else 0