[Programmers] #120912 - 7의 개수 [Java][C++][Python]
[Programmers] #120912 - 7의 개수 [Java][C++][Python]
1. 아이디어
정수 배열 array에서 7의 개수를 구하는 문제로 array의 각 정수에 대해 10으로 나눈 나머지가 7이면 개수를 세고 몫만 취하는 과정을 반복하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N \times D)$ | $O(1)$ |
($N$ = array의 길이, $D$ = 원소 x의 자릿수 $\approx \log_{10} x$. Python은 각 원소를 str(x)로 변환하므로 공간 $O(D)$)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int solution(int[] array) {
int cnt = 0;
for (int x : array) {
while (x > 0) {
if (x % 10 == 7) cnt++;
x /= 10;
}
}
return cnt;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <bits/stdc++.h>
using namespace std;
int solution(vector<int> array) {
int cnt = 0;
for (int x : array) {
while (x > 0) {
if (x % 10 == 7) cnt++;
x /= 10;
}
}
return cnt;
}
1
2
def solution(array):
return sum(str(x).count("7") for x in array)
각 원소를 문자열로 변환 후 count로 7의 개수를 세는 방식으로 해결했다.
This post is licensed under CC BY 4.0 by the author.