1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※(注記) 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
int 값을 String으로 변환하여 8을 찾아야겠다고 생각했는데, 길가의풀님도 그렇게 하셨네요! 파이썬 초보인데 길가의풀님 코드의 count('8')을 보고 저도 적용해보았습니다. 뭔가 find() 메소드가 있을거라 생각했었습니다 ^^;
>>> str(list(range(1,10001))).count('8')
2014年06月17日 09:54
import java.util.stream.IntStream;
public static void main(String[] args) {
System.out.println(String.format(">> %d", foo()));
}
public static long foo(){
//return IntStream.range(1, 10000).map(x -> String.valueOf(x).replaceAll("[0-79]", "").length()).sum();
return IntStream.rangeClosed(1, max)
.map(x -> (int)(String.valueOf(x).chars().filter(ch -> ch == '8').count()))
.sum();
}
java 8 버전입니다.
2014年07月30日 18:33
Stopwatch sw1 = Stopwatch.StartNew();
int cnt = Enumerable.Range(1, 10000).Sum(k => k.ToString().Count(z => z == '8'));
sw1.Stop();
Console.WriteLine($"Elapsed MillSecond : {sw1.ElapsedMilliseconds}, Value : {cnt}");
Elapsed MillSecond : 4, Value : 4000
2016年11月23日 04:30
'''
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※(注記) 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
'''
# for문으로 하나하나 확인
count = 0
for i in range(10000): # [0...9999]
for j in str(i):
if j == '8':
count += 1
print(count)
# 또는
print(str(list(range(10000))).count('8'))
# 8*** -> 000~ 999 -> 1000개
# *8** -> 000~ 999 -> 1000개
# **8* -> 000~ 999 -> 1000개
# ***8 -> 000~ 999 -> 1000개
# 4000개가 답이다.
풀이 작성