🔍 문제
Given an array nums of integers, return how many of them contain an even number of digits.
nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
🖥 실행
1) Answer
class Solution:
def findNumbers(self, nums: List[int]) -> int:
cnt = 0
evenList = []
for i in nums:
while i // 10 > 0:
i = i //10
cnt += 1
cnt += 1
if cnt % 2 == 0:
evenList.append(cnt)
cnt = 0
return len(evenList)
2) Better Solution
class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([x for x in nums if len(str(x)) % 2 == 0])
'Coding test > LeetCode' 카테고리의 다른 글
[LeetCode] Height Checker (0) | 2022.05.20 |
---|---|
[LeetCode] Move Zeroes (0) | 2022.05.20 |
[LeetCode] Replace Elements with Greatest Element on Right Side (0) | 2022.05.20 |
[LeetCode] Valid Mountain Array (0) | 2022.05.20 |
[LeetCode] Merge Sorted Array (0) | 2022.05.20 |