Coding Exercise: Sum of Digits in the Minimum Number
- 时间:2020-09-25 11:32:47
- 分类:网络文摘
- 阅读:154 次
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: 0Explanation:
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: 1Explanation:
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 <= A.length <= 100
- 1 <= A[i].length <= 100
C++ min_element
Using min_element() in Modern C++, you can easily get the minimal element between two iterator ranges instead of writing a for loop. The third parameter is an optional one that you can provide the customize comparator.
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Solution { public: int sumOfDigits(vector<int>& A) { // int v = *min_element(begin(A), end(A), [](auto a, auto b) { return a < b; }); int v = *min_element(begin(A), end(A)); int r = 0; while (v > 0) { r += v % 10; v /= 10; } return 1 - r % 2; } }; |
class Solution {
public:
int sumOfDigits(vector<int>& A) {
// int v = *min_element(begin(A), end(A), [](auto a, auto b) { return a < b; });
int v = *min_element(begin(A), end(A));
int r = 0;
while (v > 0) {
r += v % 10;
v /= 10;
}
return 1 - r % 2;
}
};Python
Similarly, a little bit verbose (in Python3):
1 2 3 4 5 6 7 8 9 | class Solution: def sumOfDigits(self, A: List[int]) -> int: x = min(A) S = 0 while x > 0: S += (x % 10) x //= 10 # make sure the integer division #return 0 if ((S % 2) == 1) else 1 return 1 - S % 2 |
class Solution:
def sumOfDigits(self, A: List[int]) -> int:
x = min(A)
S = 0
while x > 0:
S += (x % 10)
x //= 10 # make sure the integer division
#return 0 if ((S % 2) == 1) else 1
return 1 - S % 2Alternatively, with one-liner in Python:
1 2 3 | class Solution: def sumOfDigits(self, A: List[int]) -> int: return 1 - sum(map(int, str(min(A)))) % 2 |
class Solution:
def sumOfDigits(self, A: List[int]) -> int:
return 1 - sum(map(int, str(min(A)))) % 2or:
1 2 3 | class Solution: def sumOfDigits(self, A: List[int]) -> int: return 1 - sum(int(c) for c in str(min(A))) % 2 |
class Solution:
def sumOfDigits(self, A: List[int]) -> int:
return 1 - sum(int(c) for c in str(min(A))) % 2–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:广东电视台房产频道直播「高清」 广东岭南戏曲频道直播「高清」 嘉佳卡通卫视直播「高清」 广东电视台4K超高清频道直播_南方电视台综艺频道TVS3直播「高清」 广东电视台国际频道直播「高清」 南方购物频道直播_南方购物电视购物直播「高清」 广东电视台现代教育频道直播「高清」 广东经济科教频道直播_南方经济科教频道直播「高清」 大湾区卫视直播_广东南方电视台TVS2在线直播「省内版」 广东电视台影视频道直播_南方电视台影视频道TVS4直播「高清」
- 评论列表
-
- 添加评论