[Programmers] #120912 - 7의 개수 [Java][C++][Python]
[Programmers] #120912 - 7의 개수 [Java][C++][Python]
1. 아이디어
배열의 원소를 십진수로 썼을 때 나오는 숫자 7의 총 개수를 구하는 문제다. 77에는 7이 두 번 들어 있으므로 원소 자체가 7인지가 아니라 각 자리가 7인지를 세야 한다.
2. 코드
풀이 [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)
This post is licensed under CC BY 4.0 by the author.