Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1085.html

1085. Sum of Digits in the Minimum Number

Level

Easy

Description

Given an array A of positive integers, let S be the sum of the digits of the minimal element of A.

Return 0 if S is odd, otherwise return 1.

Example 1:

Input: [34,23,1,24,75,33,54,8]

Output: 0

Explanation:

The minimal element is 1, and the sum of those digits is S = 1 which is odd, so the answer is 0.

Example 2:

Input: [99,77,33,66,55]

Output: 1

Explanation:

The minimal element is 33, and the sum of those digits is S = 3 + 3 = 6 which is even, so the answer is 1.

Note:

  1. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 100

Solution

Loop over the array A to find the minimum number. Then calculate the sum of the digits of the minimum number. Finally check whether the sum is odd or even, and return 0 or 1 respectively.

  • class Solution {
        public int sumOfDigits(int[] A) {
            int min = Integer.MAX_VALUE;
            for (int num : A)
                min = Math.min(min, num);
            if (min == 0)
                return 1;
            int sum = 0;
            int temp = min;
            while (temp > 0) {
                sum += temp % 10;
                temp /= 10;
            }
            return sum % 2 == 0 ? 1 : 0;
        }
    }
    
  • // OJ: https://leetcode.com/problems/sum-of-digits-in-the-minimum-number/
    // Time: O(N)
    // Space: O(1)
    class Solution {
    public:
        int sumOfDigits(vector<int>& A) {
            int n = *min_element(begin(A), end(A)), sum = 0;
            while (n) {
                sum += n;
                n /= 10;
            }
            return 1 - sum % 2;
        }
    };
    
  • class Solution:
        def sumOfDigits(self, nums: List[int]) -> int:
            x = min(nums)
            s = 0
            while x:
                s += x % 10
                x //= 10
            return 0 if s % 2 else 1
    
    
    
  • func sumOfDigits(nums []int) int {
    	x := 100
    	for _, v := range nums {
    		if v < x {
    			x = v
    		}
    	}
    	s := 0
    	for ; x > 0; x /= 10 {
    		s += x % 10
    	}
    	return s&1 ^ 1
    }
    

All Problems

All Solutions