Leetcode [1085] - Sum of Digits in the Minimum Number (Java Solution)

Rugved avatar

Rugved

Leetcode [1085] - Sum of Digits in the Minimum Number (Java Solution)
Category: Easy
What is used: Arrays, Linear Search

Question

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

This is a easy problem. The 3 steps to solve this problem should be:
1. Find the minimum of the array - I used Linear Search O(n)
2. Find the sum of the minimum number - The standard way of modulo 10 and divide by 10. O(n)
3. Check if sum is odd - Simple if-else statement

```
class Solution {
public int sumOfDigits(int[] A) {

    //Find minimum
    int min = Integer.MAX_VALUE;
    for(int i = 0; i < A.length; i++){
        if(A[i] < min){
            min = A[i];
        }
    }
    int n = 0;
    int sum = 0;
    
    //Sum of minimum
    while(min > 0){
        n = min % 10;
        sum = sum + n;
        min = min / 10;
    }
    
    //Odd-Even Check
    if(sum % 2 != 0){
        return 0;
    }else{
        return 1;
    }
}

Time complexity:

The time complexity of this code is O(n)

Submission Details:

Runtime: 0 ms, faster than 100.00% of Java online submissions for Sum of Digits in the Minimum Number.
Memory Usage: 34.3 MB, less than 100.00% of Java online submissions for Sum of Digits in the Minimum Number.

Rugved avatar
Written By

Rugved

Android Developer based in Los Angeles trying to be improve programming skills!
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.