跳转至

1085. 最小元素各数位之和 🔒

题目描述

给你一个正整数的数组 A

然后计算 S,使其等于数组 A 当中最小的那个元素各个数位上数字之和。

最后,假如 S 所得计算结果是 奇数 ,返回 0 ;否则请返回 1。

 

示例 1:

输入:[34,23,1,24,75,33,54,8]
输出:0
解释:
最小元素为 1 ,该元素各个数位上的数字之和 S = 1 ,是奇数所以答案为 0 。

示例 2:

输入:[99,77,33,66,55]
输出:1
解释:
最小元素为 33 ,该元素各个数位上的数字之和 S = 3 + 3 = 6 ,是偶数所以答案为 1 。

 

提示:

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

解法

方法一:模拟

我们先找到数组中的最小值,记为 \(x\)。然后计算 \(x\) 的各个数位上的数字之和,记为 \(s\)。最后判断 \(s\) 是否为奇数,若是则返回 \(0\),否则返回 \(1\)

时间复杂度 \(O(n)\),空间复杂度 \(O(1)\)。其中 \(n\) 为数组的长度。

1
2
3
4
5
6
7
8
class Solution:
    def sumOfDigits(self, nums: List[int]) -> int:
        x = min(nums)
        s = 0
        while x:
            s += x % 10
            x //= 10
        return s & 1 ^ 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public int sumOfDigits(int[] nums) {
        int x = 100;
        for (int v : nums) {
            x = Math.min(x, v);
        }
        int s = 0;
        for (; x > 0; x /= 10) {
            s += x % 10;
        }
        return s & 1 ^ 1;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
public:
    int sumOfDigits(vector<int>& nums) {
        int x = *min_element(nums.begin(), nums.end());
        int s = 0;
        for (; x > 0; x /= 10) {
            s += x % 10;
        }
        return s & 1 ^ 1;
    }
};
1
2
3
4
5
6
7
func sumOfDigits(nums []int) int {
    s := 0
    for x := slices.Min(nums); x > 0; x /= 10 {
        s += x % 10
    }
    return s&1 ^ 1
}

评论

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy