공지: 기존 사이트는 old.codingdojang.com에서 확인할 수 있으며, 2026년 8월 3일 종료됩니다.
이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

구글 입사문제 중에서

1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?

8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)

2014/02/14 01:03

pahkey

여러 알고리즘이 존재할테고, 답도 여러가지인데...구글이 원했던, 혹은 가장 점수를 많이 줬던 정답은 뭘지 매우 궁금?궁금? - 예강효빠, 2017/05/24 01:30
경우의 수로 풀면 3번의 반복만으로 풀수 있어요 ^^ - 최재학, 2019/08/07 11:20

879개의 풀이가 있습니다.

음....

10,000 에는 8 이 없으니 무시하고, 1 부터 9999 까지

X X X 8 인 경우 : 1,000개 ( X X X 는 세자리이므로 0 0 0 ~ 9 9 9 까지 천개)

X X 8 X 인 경우 : 1,000개 ( X X X 는 세자리이므로 0 0 0 ~ 9 9 9 까지 천개)

X 8 X X 인 경우 : 1,000개 ( X X X 는 세자리이므로 0 0 0 ~ 9 9 9 까지 천개)

8 X X X 인 경우 ; 1,000개 ( X X X 는 세자리이므로 0 0 0 ~ 9 9 9 까지 천개)

총 4,000 개 아닌가?

2014/02/14 17:08

jake kim

+6 아마 입사문제라면, 이렇게 풀이 방식을 제시하는게 정석일 것 같네요. 네이버도 입사문제로 창의력을 발휘한 수학문제 풀기? 이런거 내는데, 구글도 아마 코딩을 하라는 의미는 아닐거 같아요. - 초록빛희망, 2014/02/14 17:12
네, 초록빛희망님 말씀에 동감합니다. ^^ 하지만 코딩으로 풀어봐도 재미있네요. - pahkey, 2014/02/14 17:17
그런데, 위의 경우 첫번째케이스와 두번째케이스에 중복된 값이 발생하지 않나요? 1188의 경우 첫번째와 두번째 모두 해당되는것 같습니다. - pahkey, 2014/02/16 13:05
+4 길가의풀 님 중복된값을 카운팅하기 때문에 문제에 나와있는 조건 "8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다." 를 만족할 수 있는 것 이라고 생각합니다. 1188의 경우 2여야겠죵 - Yoon Jake, 2014/02/16 13:25
+2 아.. 그렇군요. 8888의 경우 첫번째 케이스에서 1개가 카운트되고, 두번째 케이스에서 또 1개가 카운트되고,, 총 4개가 카운트되는 원리네요.. 한참 생각했네요..ㅎ - pahkey, 2014/02/16 15:14
+1 이것이 가장 훌륭한 답이네요. - 박연오, 2014/02/19 01:07
멋지네요.. 생각의 전환! - 임시, 2014/09/26 12:26
재밌게 잘 보고 갑니다. - 이성환, 2014/10/08 11:07
키야~ㅋㅋ 이정도문제는 컴퓨터도 필요없다 이겁니까? ㅋㅋㅋㅋㅋㅋ - kihyun lee, 2017/06/15 21:15
숫자의 개수를 구하는 것이 아니라 총 8의 개수를 구하는 것이라 아닌것 같아요 ^^; - 최재학, 2019/08/07 11:21

0000부터 9999라고 생각하고 4자리숫자가 10000개이므로 들어가는 숫자의개수는 4만개 0부터 9까지 10개의 숫자가 같은 비율로 들어가니 4만을 10으로 나누면 4천!

2014/02/19 09:45

장 한솔

와우~ 감동이네요!! - pahkey, 2014/02/19 09:49
와~~ 더 지니어스에요 ^_^ - 무명소졸, 2014/03/07 15:56
와쩐다 ㅋㅋ - 한기우, 2015/11/24 16:40
오줌쌌다.. - Kookeedd, 2019/03/19 11:37

파이썬 2.7 입니다.

print str(range(1,10001)).count('8')

2014/02/14 14:00

pahkey

죄송한데 파이썬 초보라 이해가 잘 안됩니다. 위의 코드를 넣고 돌려봤는데(print에 괄호 넣고) 0 이 나오더라구요(python 3.3). 제가 뭔가 잘못한걸까요? str(range(1,10001)) 넣으면 '1234567891011....'이 나오나요? - 에밀로, 2014/02/19 05:18
파이썬 2.7.6 잘 됩니다. 파이썬 2.7.6에서 str(range(1,10001))하시면 "[1,2,3,...,10000]" 됩니다 - Lee SunYeop, 2014/02/19 05:24
답변 감사합니다. 그럼 버전의 문제인듯한데, 3.3버전에서 str(range(1,10001))을 하려면 어떻게 해야할까요? - 에밀로, 2014/02/19 05:35
+8 답을 찾았습니다. print(str(list(range(1,10001))).count('8')) 로 하면 되는군요. - 에밀로, 2014/02/19 09:20
오 저는 숫자 하나 하나의 '8'의 갯수를 찾고 그 것의 갯수를 더하는 방법을 택했는데, list에 넣고 한번에 세는 것이 더 간단하고 좋은 것 같네요~ 간결하고 멋져요!! - lkungs, 2016/08/16 17:41
멋진 발상의 전환입니다. - Kim J.S., 2016/10/29 18:36

JAVA

public class CountingEight {
    public static void main(String[] args) {
        for (int i=0; i<=10000; i++){
            searchEight(i);
        }
        System.out.println("1에서 10,000 사이에 존재하는 8의 개수는? "+count);
    }
    private static int count = 0;
    public static void searchEight(int num){
        if (num%10==8) count++; 
        if (num>10) searchEight(num/10);
    }
}

1에서 10,000 사이에 존재하는 8의 개수는? 4000

2015/02/24 18:33

그린구름

파이썬 3.5로 풀었습니다.

print(str(list(range(1, 10001))).count('8'))

2016/11/22 01:24

Analyticsstory

파이썬은 한줄로 가능하군요!!! @_@ 제 능력으로는 이렇게 밖에.... 하아~~

int count = 0;
for(int i = 1; i < 10001; i++)
{
    for(int j = i; j > 0; j /= 10)
    {
        if(j % 10 == 8)
        {
            count++;
        }
    }
}

2014/02/14 16:10

Nemorino

멋진 방법이네요. 감탄했습니다. ^^ - pahkey, 2014/02/14 16:29
+1 아래 파이썬 해법은 알고보면 무척 단순합니다. 숫자 리스트를 모두 문자열로 변환해서 합친다음에 그 합쳐진 문자열에서 8이라는 숫자가 몇개인지 조사하는 방법입니다. - pahkey, 2014/02/14 16:44
  1. 8이 들어가지 않는 자리에 0~9까지 8을 제외한 값을 넣는다.
  2. 경우의 수만큼 곱한다.
  3. 8이 들어가는 자릿수만큼 곱한다.

8이 한번 나올 때

8000 0800 0080 0008

9x9x9x4 2916번

8이 2번 나올 때

8800 8080 8008 0880 0808 0088

9x9x6x2 972번

8이 3번 나올 때

8880 8088 8808 0888

9x4x3 108번

8이 4번 나올 때

8888 4번

8은 4000번 나온다.

2014/09/30 21:38

이 민석

정말 다양한 풀이가 존재하는군요 ^^ - pahkey, 2014/09/30 23:08
int main()
{

   int i,j,n,m;
   int sum;
   sum = 0;

   for (i=0; i<10; i++){
       for(j=0; j<10; j++){
                for (n=0; n<10; n++){
                    for(m=0; m<10; m++){
                             if( m == 8 ){sum = sum+1;}
                             if( n == 8){sum = sum+1;}
                             if ( j == 8){sum = sum+1;}
                             if( i == 8 ){sum = sum+1;}
                    }
              }
       }


   }
   printf("1~10000까지 8을 가진 숫자의 갯수는 %d 이다.\n",sum);
}

이제 C 공부하기 시작한 초보입니다. 배운 범위에서는 이렇게 하면 되네요.

2015/12/07 17:59

Son Geoffrey

Ruby

puts ("1".."10000").to_a.join.count("8")

문자열 Range "1" 부터 "10000" 까지를, Array로 변환, Array를 하나의 문자열로 합치고, "8"이라는 문자를 Count 한 후, 결과를 출력한다.

여러분 루비하세요. 자바가 한문이라면 루비는 한글입니다.

2014/05/05 14:26

김PD

오~ 문자열 "1"도 열거형처럼 동작하나요?? "10" 다음에 "11"인걸 어떻게 처리하는지 궁금하네요 - Han Jooyung, 2016/11/10 09:29
+1 range클래스는 주어진 값의 #succ로 다음값을 획득하게 되어있습니다. String#succ는 오른쪽 끝문자의 숫자/영문 여부를 확인한 뒤 숫자면 숫자범위에서만 값증가, 영문이면 영문내에서 값증가, 혼합형이면 ascii로 증가시킵니다. 값을 증가시키는 중에 최대값을 넘어서는 carry가 발생하면 올림자리 값을 증가시켜줍니다. ("1a".."zz")는 range의 시작값이 숫자문자이므로 1a,1b...,1z,2a,..9z까지 만들어 주는 식이죠. 엑셀문자열 배열은 ("A".."ZZZ") 와 같이 만들 수 있습니다. http://bit.ly/28UZ60o - #succ 설명 : http://ruby-doc.org/core-2.3.1/String.html#method-i-succ - c source : https://rxr.whitequark.org/mri/source/string.c?v=2.1.2 3254라인 - rk, 2016/11/10 12:12

Java로 풀어보았습니다.

각 자리수에 대해 8인지 검사하고 8이면 cnt값을 하나씩 증가시켜서 8의 개수를 구하는 코드입니다.

class Count8 {
    public static void main(String[] args) {
        int cnt = 0;

        for(int i = 1; i < 10000; i++ ) {
            if( i % 10 == 8 ) cnt++;
            if( (i / 10) % 10 == 8 ) cnt++;
            if( (i / 100) % 10 == 8 ) cnt++;
            if( (i / 1000) % 10 == 8 ) cnt++;
        }

        System.out.println("result : " + cnt);
    }
}

2014/08/15 10:13

yjpark

print ''.join(str(x) for x in range(1, 10001)).count('8')

Python(2.7.9)으로 작성하였습니다.
결과는 4,000으로 확인되었습니다.

2015/11/18 16:59

如 月華

자바스크립트 입니다.

function getEights() {
    var count = 0;
    for(i = 1; i <= 10000; i++) {
        count += ((i + "").split(/8/g).length - 1);
    }
    console.log(count);
}

2014/02/15 02:04

Park Jung Wook

8로 split하는 재밌는 방법이네요 ^^ - pahkey, 2014/02/15 10:31
<?php
echo substr_count(join('', range(1,10000)), 8);
?>

2014/02/19 09:09

송 영호

int 값을 String으로 변환하여 8을 찾아야겠다고 생각했는데, 길가의풀님도 그렇게 하셨네요! 파이썬 초보인데 길가의풀님 코드의 count('8')을 보고 저도 적용해보았습니다. 뭔가 find() 메소드가 있을거라 생각했었습니다 ^^;

>>> str(list(range(1,10001))).count('8')

2014/06/17 09:54

전 수현

str과 list의 순서가 바뀌어야 하지 않을까요? - 최정진, 2016/12/23 10:15
순서보다는 range(1,10001) 가 list type 이라서 안써도 되네요. >>> str(range(1,10001)).count('8') Counter 써서 해봤습니다. from collections import Counter Counter(str(range(1,10001)))['8'] - 전 수현, 2016/12/26 22:08

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

이 정우

    Sub Main()
        Console.WriteLine("Result: " & (From c As Char In String.Join("", Enumerable.Range(1, 10000)).ToArray Where c = "8"c Select c).Count)

        Console.ReadLine()
    End Sub

Linq를 이용했습니다.

정답: 4000

2015/06/12 15:13

Steal

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

lee jaekyoon

-- ORACLE SQL
SELECT SUM(CNT)
  FROM (SELECT LENGTH(TO_CHAR(LEVEL)) - NVL(LENGTH(REPLACE(TO_CHAR(LEVEL),'8','')),0) CNT
          FROM DUAL
        CONNECT BY LEVEL <= 10000)
;


2017/02/17 11:20

진평수

'''
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개가 답이다.

2018/06/11 14:14

재즐보프

print(sum([str(num1).count('8') for num1 in range(1,10000)]))

2018/09/01 15:14

오왕씨

print(str(list(range(1, 10001))).count('8'))

2019/04/05 15:09

비밀

print(str(list(range(1, 10001))).count('8'))

2019/06/17 16:44

Hwaseong Nam

result = 0

for i in range(1, 10000):
    a = list(str(i))
    for m in a:
        if "8" in m:
            result += 1

print(result)

2020/02/06 16:03

김희준

sum=0

for i in range (1,10001):
ii=str(i)
for j in range (0,len(ii)):
if int(ii[j])==8:
sum=sum+1

print (sum)

2020/03/12 01:32

Buckshot

# List comprehension 이용 
nums = [int(a) for x in range(1,10001) for a in str(x)]
count = sum(1 for n in nums if n == 8)
print(count)

2023/07/18 17:05

Dongyoon Kim

String temp = "";
int count = 0;

for(int i = 1; i < 10001; i++)
{
    temp = temp.concat(String.valueOf(i));
}

for(int j = 0; j < temp.length(); j++)
{
    if(temp.charAt(j) == '8')
    {
        count++;
    }
}

2014/02/14 16:58

Nemorino

+1 길가의풀님 방법으로 자바에 적용해봤습니다. 길가의풀님 감사합니다. ^^ - Nemorino, 2014/02/14 17:01

php의 경우는 요렇게 네요 ^^

$tmp = 0;
for ( $i = 1 ; $i <= 10000 ; $i++ ){
    $tmp += substr_count($i, "8");
}
echo $tmp;

// 4000

2014/02/14 18:39

우너세

php도 참 편리한 언어네요 - pahkey, 2014/02/14 21:34

C 코드입니다.

#include <stdio.h>

int main()
{
  int i;
  int count[4] = {1};
  int v = 9;
  int sum = 1;
  for (i = 1; i < 4; i++) {
    count[i] = v + count[i - 1] * 10;
    v *= 10;
    sum += count[i];
  }

  printf("count of 8 from 1 to 10,000: %d\n", sum);
  return 0;
}

2014/02/14 23:22

이벽산

i자리의 수들 중 8의 개수를 알면 i+1자리의 수들 중 8의 개수를 알 수 있습니다. - 이벽산, 2014/02/14 23:25

Python 으론 이렇게 단순한데요. 근데 이렇게 간단한 답을 원하는게 아니라 어떻게 풀어야 하는지 방식을 설명해야 될것 같습니다.

list=""
for i in range(1,10000): list = list + str(i)
print list.count('8')   

2014/02/19 00:57

Kim Daniel

Clojure 코드입니다.

(count (filter #{\8} (reduce str (map str (range 1 10001)))))

2014/02/19 01:03

박연오

암호같은 Clojure 코드도 요 문장만큼은 파이썬과 매우 흡사하네요.. 신기신기.. - pahkey, 2014/02/19 01:29

PHP입니다.

<?php
$c = 0;
for($i=0;$i<10000;$i++){
   for($j=0;$j<strlen($i);$j++){
     if(substr($i,$j,1)==8){
       $c++;
     }
   }
}
echo $c;
?>

2014/02/19 01:50

Harold Kim

Ruby입니다

puts (8..1000).map(&:to_s).join.count('8')

2014/02/19 02:42

Kim Jaeju

(총자리수 - 1) * 10 ^ (총자리수 - 2)

예:

100 까지 8 의 총 갯수 -> 2 * 10 ^ 1 = 20

1000 까지의 8 의 총 갯수 -> 3 * 10 ^ 2 = 300

10000 까지의 8 의 총 갯수 -> 4 * 10 ^ 3 = 4000

2014/02/19 03:36

Yang's

>>> sum(b.count('8') for b in [str(a) for a in xrange(1,10000+1)])
4000

Python 2.7.6

2014/02/19 05:25

Lee SunYeop

print ''.join(map(str,xrange(1,10001))).count('8')

Python 2.7.6

2014/02/19 06:17

Lee SunYeop

scala> (1 to 10000).map(_.toString.count(_=='8')).sum
res0: Int = 4000

2014/02/19 08:39

성큼이

루푸 없이 입력한 숫자까지 갯 수 구하는 프로그램 입니다.


#include "stdafx.h"
#include <math.h>
int Get8Count(int nValue)
{
    int nCount = 0;
    int nDigit = log10((double)nValue);
    if(nDigit ==0 || nValue ==0)
        return nValue >=8;
    int nLast = ((int)(nValue/pow(10.,nDigit))) ;
    nCount += nDigit * pow(10.,(nDigit-1)) *nLast;
    if(nLast == 8)
        nCount++;
    return nCount+Get8Count(nValue%(int)(pow(10.,nDigit)));

}
int _tmain(int argc, _TCHAR* argv[])
{
    while(1)
    {
        printf("?");
        int nMax = 0;
        int nCount = 0;
        scanf("%d",&nMax);
        printf("\n%d\n",Get8Count(nMax));

    }
    return 0;
}

2014/02/21 14:59

김 영남

c# 입니다.

int cnt = 0;
for(int i = 0 ; i < 10000; i++)
     for(int j = 0; j < i.ToString().Length; j++)
           if (i.ToString()[j].ToString().Contains("8")) cnt++;

System.Console.WriteLine("cnt : " +cnt);

2014/02/27 13:58

강두루

Ruby.

1.upto(10000).reduce(0){|s, i| s += i.to_s.scan(/8/).length} 

2014/02/28 10:01

nacyot

파이썬입니다.

eightTotal = 0
for numb in range(0,9999):
    eightTotal = eightTotal + str(numb).count('8')

print(eightTotal)

2014/03/10 16:09

무명소졸

clojure

(->> (range 1 10000)
     (mapcat #(-> % str seq))
     (filter #{\8})
     count)

2014/03/23 05:21

김 은평

def count8():
    cnt = 0
    for i in range(1, 10001):
        cnt += str(i).count('8')
    return cnt


def count8_1(sum=0, n=1):
    if n>4: return sum
    sum = sum*10 + 10**(n-1)
    return count8_1(sum, n+1)


def count8_2():
    cnt = 0
    cur = 1
    while cur <= 4:
        cnt = (cnt * 10 + 10**(cur-1))
        cur = cur+1
    return cnt

2014/03/26 02:36

Mun Kyeongsam



    count = 0
    for i in range(10000):
        sentence = str(i)
        for j in range(len(sentence)):
            if sentence[j] == '8':
                count+=1

    print("%d", count)

Python 한줄 코드보고 놀라움을 감추지 못하고있네요. 저도 언젠가 저런날이 오길...

전 7줄이나... int -> str 으로 변환해서 '8'을 찾았습니다.

2014/03/30 15:31

Hwang Lindsey

cou = 0

for i in range(0, 10):
    for j in range(0, 10):
        for k in range(0, 10):
            for l in range(0, 10):
                m=[i,j,k,l]
                cou=cou+m.count(8)

print(cou)

약간의 힌트를 얻어 위에처럼 코딩이라고 부르기에 부끄러운 코딩했습니다.
다른 분 보니 파이썬으로 아주 쉽게 했던데..ㅎㅎ
같은 도구를 가지고도 이렇게 비효율적으로 할 수 있다는 제 자신에 놀랐습니다. ㅎㅎ

2014/04/28 17:50

이 상한

파이썬입니다. 초보라 한줄로는 안되네요...

count_8 = 0
for num in range(1,10001):
        count_8 = count_8 + str(num).count('8')
print("result = %d" % count_8)

결과 값

result = 4000

2014/04/29 17:18

재민스

오늘 밀고가는 자바스크립트와 정규식 조합입니다.

var c = 0;
for(var i = 0 ; i <= 10000 ; i++) {
    (i + "").replace(/[8]+/g, function (match) {
        c += match ? match.length : 0;
    });
}
console.log(c);

2014/04/29 20:23

Lee MooYeol

cnt = 0
for i in range(1, 10000, 1):
        a = str(i)
        j = ""
        for j in a:
                if j == "8":
                        cnt += 1
print cnt

2014/05/16 14:23

superarchi

와... 풀고 나서 다른 분들 글 보고 경악을 금치 못하겠네요.. 한줄로 퉁이라니 ㅋㅋㅋ

난 뭐 이리 복잡하게 짠거지? ㄷㄷㄷ

def countEight(m):
    eightCnt = 0
    for i in range(1, m+1) :
        eightCnt = eightCnt + checkEight(i)
    return eightCnt

def checkEight(i) :
    if i > 10 :
        if i % 10 == 8 :
            return checkEight(i/10) + 1
        else :
            return checkEight(i/10)
    else :
        if i == 8 :
            return 1
        else : 
            return 0

if __name__ == '__main__':
    print countEight(10000)

2014/05/22 17:39

이 성욱

파이썬 3.2.5 기준입니다.

count = 0
for i in range(1,10001):
    count += str(i).count('8')
print(count)

2014/05/24 01:29

Youngjin Shin

파이썬으로 간단하게 나타냈습니다.

count = 0
for number in range(1,10001):
    for ch in str(number):
        if ch == '8':
            count += 1
print(count)

2014/05/24 20:01

Heong Jun Yoo

//javascript
function test(a){
  return (a.toString().length-1)*(a/10);
}
//test
for (var j=0 ; j<10; j++){
    var input = Math.pow(10, j);
    console.log( "%d -> %d ", input, test( input )) ;
}

결과

1 -> 0
10 -> 1
100 -> 20
1000 -> 300
10000 -> 4000
100000 -> 50000
1000000 -> 600000
10000000 -> 7000000
100000000 -> 80000000
1000000000 -> 900000000

2014/05/30 18:11

이 정우

def count_n(num, n):
    tot_count = 0
    str_n = str(n)
    for i in range(0, num + 1):
        temp_str = str(i)
        tot_count += temp_str.count(str_n)
    return tot_count

n = 8
tot_num = count_n(10000, n)
print("total number of %d is %d" %(n, tot_num))

2014/06/19 16:25

Roy

정답은 4000개입니다

cnt = 0
for i in range(1,10000):
    for j in str(i):
        if j is '8':
            cnt += 1
print cnt

2014/07/01 15:44

황 성호

#include <stdio.h>


int count(int n)
{
    int temp;
    int i;
    int count = 0;

    for(i = 0; i <= n; i++)
    {
        temp = i;
        while(temp > 0)
        {
            if(temp % 10 == 8) count++;

            temp /= 10;
        }

    }

    return count;
}

int main(void )
{
    printf("%d\n", count(10000));

    return 0;
}

2014/07/06 20:02

고 상우

길이는 길지만, 하나하나 루프 돌리면서 개수를 세는 것보다는 훨씬 빠르게, 10^20 이상의 큰 숫자에서도 개수를 구할 수 있는 코드입니다. ( by Python )

class ec_2(object):

    """second algorithm : can calculate faster than ec_1 algorithm,
       regardless of the magnitude of the given number.

       used the fact that 10**n contains n*10**n-1 of 8."""

    def __init__(self,k):
        self.k = k

    def check(self):
        key = str(self.k)
        n = len(key)-1

        eight = 0

        i=0
        while i<len(key):
            if int(key[i])<8:
                eight += int(key[i])*(n-i)*(10**(n-i-1))
                i += 1

            elif int(key[i])==9:
                eight += 9*(n-i)*(10**(n-i-1))
                eight += 10**(n-i)
                i += 1

            else:
                eight += 7*(n-i)*(10**(n-i-1))

                if i==n:
                    eight += 1
                else:
                    eight += self.k % 10**(n-i)
                i = n+2

        return eight

2014/07/08 02:19

신 상국

가장 단순한 방법으로 하였습니다. 다른 분들의 방법을 보니, 대단하신 분들이라고 느껴지네요.

1~10000까지 모든 숫자를 일렬로 세우고, 문자열로 변환후, 8을 세는 방법도 있겠네요.


import unittest

def method1():
    count = 0
    for i in range(1, 10001):
        if str(i).count("8") > 0:
            count += str(i).count("8")
    return count

def method2():
    count = 0
    for i in range(1, 10001):
        count += str(i).count("8")
    return count    

class TestCount8(unittest.TestCase):
    def test_methods(self):
        self.assertEqual(method1(), 4000)
        self.assertEqual(method2(), 4000)

if __name__ == "__main__":
    unittest.main()

2014/07/18 08:39

이 정구

(1 to 10000).map ( _.toString.filter(x=>x.asDigit==8).length ).sum

스칼라 코드입니다.

2014/07/25 14:58

goodgene

파이썬으로 풀어봤어요

print str(range(1,10000)).count('8')

2014/08/12 19:20

Cha Semo

java 입니다.

int totalCnt = 0;

// 1부터 10000까지 루프
for(int i=1; i<10000; i++){

    // i를 String 형태로 변환
    String str = String.valueOf(i);

    // String형태에서 8문자가 있는지 확인
    if(str.contains("8")){

        // 8이 있다면 현재 변환된 String의 길이값으로 루프
        for(int j=0; j<str.length(); j++){

            //  문자형태로 변환해서 8인지 확인
            if('8' == str.charAt(j)){
                totalCnt++;
            }
        }
    }
}

System.out.println("총 " + totalCnt + "개");

2014/08/13 16:06

Go JaeSik

1~10000범위의 숫자를 문자열, 즉 str로 하여금 싱글쿼터 안에 8을 넣음으로써 문자열으로 인식하여 8의 갯수를 카운트 합니다.

>>> print str(range(1, 10000)).count('8')
4000

2014/08/16 22:33

이정필

c입니다. 숫자 8을 어떻게 세지 고민하다가 char형으로 바꾼다음에 세는 방법을 썼는데... 다른 분들의 풀이를 보고 나서야 %를 사용하면 된다는 사실을 깨달았네요ㅜㅜ

#include <stdio.h>
#include <stdlib.h>

#define MAX 10000

int main()
{
    int number=0, i, j=0, k;
    int count=0;
    char buffer[10]={0,};

    for(i=0;i<MAX;i++)
    {
        number++;
        itoa(number,buffer,10);
        while(buffer[j])
        {
            if(buffer[j]=='8')
            {count++;}
            j++;
        }
        for(k=0;buffer[k];k++)
        {
            buffer[k]='\0';
        }
        j=0;
    }
    printf("1부터 %d까지 8의 개수는 %d개입니다.\n", MAX, count);

    return 0;
}

2014/08/18 21:59

IM HUI-AE

        int count = 0;
        for (int i = 1; i <= 10000; i++) {
            if (i % 10 == 8)
                count++;
            if ((i / 10) % 10 == 8)
                count++;
            if ((i / 100) % 10 == 8)
                count++;
            if (i / 1000 == 8)
                count++;

        }
        System.out.println(count);


다른분들 코드 대단하네요 ..ㄷㄷ

2014/08/20 16:36

박 대성

#google_test1.py
n=0
for num in range(1,10001):
    for part in str(num):
        if part == '8':n+=1

print n

2014/08/21 19:12

안 태경

// java

// n = 10, 100, 1000 ...
// System.out.println(google(10000));  
public static int google(int n) {
    return n==0 ? 0 : 10 * google(n/10) + n/10;
}

2014/08/27 16:40

msk

오토핫키입니다. 프로그램언어선택란에도 없네요..그래서 해 봤습니다..

loop,10000
    수나열.=A_Index                   
숫자8만모음:=RegExReplace(수나열,"[^8]")   
MsgBox,% strlen(숫자8만모음) 

2014/08/28 11:53

peej

#import <Foundation/Foundation.h>

@interface Eight : NSObject
{
    int count; // 숫자의 갯수
    int num; // 어떤숫자를 확인할지
}
@end

@implementation Eight
-(id)initMember
{
    if( (self = [ super init ]) )
    {
        count = 0;
        num = 8; // 8이 몇개인지 확인하기 위해 8로 초기화
    }
    return self;
}

-(void)LoopMethod:(int)var
{
    while( var-- ) // 입력받은값이 0보다 클동안 반복
    {
        [ self CountMethod: var ]; // 입력받은수에서 8의 갯수 확인
    }
}

-(void)CountMethod:(int)var
{
    while( var > 0 ) // var/10 이 0이면 1의자리한개만 남은상황이므로 검사종료.
    {
        if( num == var % 10 ) count++;
        // 10으로 나누면 1의자릿수만 남게되는데 그게 8인지확인

        var = var / 10;
    } // 10으로 나누면 1의자리는 없어지고 10의자리가 1의자리가 된다.(몫만 취하므로)
}
-(int)count { return count; }
@end

int main(int argc, const char * argv[])
{
    @autoreleasepool {

        Eight * obj = [ [ Eight alloc ] initMember ];
        [ obj LoopMethod: 10000 ];
        NSLog(@"result = %i", [ obj count ] );
    }
    return 0;
}

2014/08/30 17:53

식빵

puts ("1".."10000").to_a.join.count("8")

위의 김PD님이 작성한 루비코드와 같은데 아예 처음부터 array로 시작합니다.

puts Array(1..10000).to_s.count('8')
puts Array(1..10000).join.count('8')

2014/09/12 10:41

정봉근

Scala; Stream, View 활용

// div10(2553) = [2553, 255, 25, 2, 0, 0, 0, ...]
def div10(n: Int): Stream[Int] = n #:: div10(n / 10)

// count8(8138) = 2
def count8(n: Int): Int = div10(n).takeWhile(_ != 0).count(_ % 10 == 8)

println((1 to 10000).view.map(count8).sum)

2014/09/13 16:33

Purluno

파이썬 입니다. 풀고 보니 이미 훨씬 아름다운 코드들이 많이 올라와 있네요 ^^;; 그래도 한번 올려 봅니다~~~

total = 0
for x in range (1,10001):
    y = str(x)
    num = y.count('8')
    total += num
print(total)

2014/09/20 21:27

돌구늬ㅋ~썬

문자열로 한자리씩 끊어 처리하는 방법이랑 각 자리수로 계산 하는 방식 2가지로 해봤습니다. JAVA 코드입니다~

package my_test;

public class T {
    public static void main(String[] args) {
        int su=10000;   
        System.out.println("자리수 계산 방식:"+eight_num(su));
        System.out.println("문자열 계산 방식:"+eight_str(su));

    }

    /**
     * 자리수 계산 방식
     */
    public static int eight_num(int num){
        int result=0;
        for(int i=0;i<=num;i++){            
            for(int j=i;0<j;){
                if(j%10==8){
                    result++;
                }
                j/=10;
            }
        }
        return result;
    }
    /**
     * 문자열 계산 방식
     */
    public static int eight_str(int num){
        int result=0;

        for(int i=1;i<=num;i++){
            String temp= String.valueOf(i);
            for(int j=0;j<temp.length();j++){
                if('8' == temp.charAt(j)){
                    result++;
                }
            }
        }
        return result;
    }   
}

2014/09/23 14:19

임시

using System;

class Program
{
    static void Main(string[] args)
    {
        int numberEightCount = 0;

        for (int i = 1; i <= 10000; i++)
        {
            char[] digits = i.ToString().ToCharArray();
            foreach (var aDigit in digits)
            {
                if (aDigit == '8')
                {
                    numberEightCount++;
                }
            }
        }

        Console.WriteLine("numberEightCount = " + numberEightCount);
    }
}

2014/09/25 16:17

보헤미안

objective c 풀었습니다. 문자열로 변환이후 각 자리수를 어떻게 구해야 하나 생각하느라 시간이 좀 걸렸네요

- (int) CountNumber:(NSString *)num
{
    self.countNum = 0;

    for(int i = 1; i<=10000; i++)//1~10000까지 숫자를 한번씩 계산합니다
    {
        NSString *temp = [NSString stringWithFormat:@"%d", i];
        //문자열로 전환
        for(int j=0; j < temp.length; j++)//그 전환한 문자열의 자릿수 만큼 반복합니다
        {
            if('8' == [temp characterAtIndex:j])//각 자리수를 체크
            {
                countNum++;
            }
        }
    }
    return countNum;
};

//main
CountNumber *myCountNum = [[CountNumber alloc] init];
        [myCountNum CountNumber:@"8"];

        NSLog(@"%d", myCountNum.countNum);


//결과
CodingDojang[965:303] 4000


2014/09/30 16:19

JeGal Gil

성능을 위해 StringBuilder를 사용했습니다

public class Main {
    public static void main(String[] ar){

        int cnt = 0;
        StringBuilder s = new StringBuilder();

        for(int i = 1; i <= 10000; i++){
            s.append(i);
        }

        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == '8')
                cnt++;
        }
        System.out.println(cnt);
    }
}

2014/09/30 23:17

천재일우

puts ("1".."10000").to_a.join.count("8")

2014/10/05 05:37

Lim Eun Chong

package Coding;

public class coding2 {
    public static void main(String args[]){
        int ard=0;  // 나누어줄 값
        int res=0;  // 계산의 결과
        int cor=0;  // 결과값, 갯수
        int incr=88; // 구해야할 값의 한계

        for(int j=0;j<=incr;j++){
            ard = j;
        for(int i=0; i<=ard;i++){
            res = ard % 10;
            ard /= 10;
            if(res == 8){
                ++cor;
            }
            res = 0;
        }
        System.out.println(cor);
        }
    }
}

2014/10/08 11:08

이성환

total = 0
for x in str(range(1,10001)):
      for n in x:
        if n == '8':
            total += 1

print total

'길가의 풀'님의 풀이를 파이썬으로 더 풀어봤습니다. 더 길어서 의미는 없습니다만ㅎ

2014/10/20 11:24

jo dong hyun

루비

a = Array(1..10000).to_s
a.count("8")

2014/10/29 14:23

Cha Semo

sum([str(x).count('8') for x in range(10001)])

2014/11/01 05:55

Justin Kang

public class CountEightMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s = "";
        char cArray[] = null;
        long cnt = 0;

        for(int i = 1; i <= 10000; i++) {
            s = Integer.toString(i);
            cArray = s.toCharArray();
            for (int j = 0; j < cArray.length; j++) {
                if (cArray[j] == '8') {
                    cnt = cnt + 1;
                }
            }
        }

        System.out.println(cnt);
    }

}

2014/11/14 22:39

김 연태

scala로 풀었습니다.

(1 to 10000).map(_.toString.count(_ == '8')).sum

2014/12/04 16:08

killbirds

#include <iostream>

using namespace std;


void main() {
    int num = 10000;
    int count = 0;

    for (num; num != 0; num--) {
        int i = num;
        while (i >= 8) {
            if (i % 10 == 8)
                count++;
            i /= 10;
        }
    }

    cout << count << endl;
}

2014/12/06 09:21

I ZG

일에서 천의 자리에 8을 꽂아넣고 나머지 숫자조합이 가능한 1000개씩 총 4천개가 됩니다만, 파이썬으로는 정직하게 다음과 같이 구해보았습니다.

print sum((str(x).count('8') for x in range(1, 10000+1)))

2014/12/11 15:11

룰루랄라

각 자리에 8이 출현할 경우의 수는..

[10, 10, 10, 1].reduce(:*) + [10, 10, 1, 10].reduce(:*) + [10, 1, 10, 10].reduce(:*) + [1, 10, 10, 10].reduce(:*)
[10, 10, 10, 1].reduce(:*) + [10, 10, 10, 1].reduce(:*) + [10, 10, 10, 1].reduce(:*) + [10, 10, 10, 1].reduce(:*)
[10, 10, 10, 1].reduce(:*) * 4
10 * 10 * 10 * 1 * 4
4000

이네요.

그냥 아무생각없이 풀면

('8'..'9998').map {|s| s.scan(/8/).size }.reduce(:+)

2014/12/12 01:11

Shim Won

펄입니다

$_=$ARGV[0];my$s=join("",1..$_);grep {$_==8},(split //,$s)

리눅스 쉘에서 다음과 같이 입력합니다

perl -e '$_=$ARGV[0];my$s=join("",1..$_);grep {$_==8},(split //,$s)' 10000
4000

2014/12/21 00:30

이병곤

howMany8 = 0
for i in range(1,10001):
    i = str(i)
    howMany8 += i.count('8')

print howMany8

2014/12/28 19:16

김슈타인

Perl

$s.=$_ for(1..10000);print $a=()=$s=~/8/g

자리 당 천번이고 뭐고 브룻 포스로 다 붙이고 8로 매치해봅니다.

2015/01/02 21:34

*IDLE*

def counter(n, max):
    #print n
    #print max
    cnt = 0

    for i in range(1, int(max)+1):
        for c in str(i):
            if str(n) == c:
                cnt +=1
    return cnt

print "카운팅 할 숫자와 최대값을 입력하세요! (예: 3,20) : "
n,max = raw_input().split(',')

cnt = counter(n,max)
print ('1부터 %s 까지 숫자 중에서 %s 은(는) 총 %s 번 나왔습니다.') % (max,n,cnt)

파이썬2.7 입니다. 답은 4000개 맞게 나오는데, 10,000까지 8만 카운트 하는게 아니라 입력받은 수 내에서 카운트 하게끔 해봤습니다.

2015/01/07 14:24

김 보근

파이썬입니다.

count = 0
for i in range(0, 10001):
    count += str(i).count('8')
print(count)

2015/01/13 15:37

Kim SangWon

Scala

(1 to 10000).map(_.toString.count(_=='8')).sum

2015/01/18 10:03

이 호연

coding by python beginner

cnt = 0
for i in range(10000):
    for s in str(i):
        if s == '8': cnt += 1
print(cnt)

2015/01/23 11:36

vegan

#!/usr/bin/python
# -*- coding: euc-kr -*-
# -*- coding: utf-8 -*-
# -*- coding: ko_KR.eucKR -*-

def main():
    cnt = 0
    for i in range(1,10000):
        sss =  str(i)
        for j in range(0,len(sss)):
            if  sss[j] == '8' :
                cnt = cnt+1
    print cnt
if __name__ == "__main__":
    main()

2015/01/26 13:29

김 휴

swift입니다.

import UIKit

var count=0

for(var i=1;i<10001;++i){ for(var j=i;j>0;j /= 10){ if(j%10 == 8){ count++ } } }

print(count)

2015/01/27 21:35

깊은물

숫자를 차례대로 문자열로 바꾼다음 그 안에서 8 이라는 숫자를 카운트 합니다.

def string_count(word):
    count=0
    list=word
    for t in list:
        if '8' == t:
            count=count+1
    return count

t_count=0
for i in range(10000):

    value=str(i)
    if '8' in value:
        t_count=t_count + int(string_count(value))
print t_count

2015/01/28 17:38

이 승훈

Python

print(sum([str(s).count('8') for s in xrange(10000)]))

2015/02/06 11:35

Kang MinSu

python 정규표현식을 이용해서 풀어봤습니다

import re

def main():
    list = []
    for num in range(10000):
        list.append(num)

    count = re.findall(r'8',str(list))
    print(len(count))

if __name__ == '__main__':
    main()

2015/02/11 21:37

amainlog

scala> (1 to 10000).map(_.toString.count(_ == '8')).sum
res8: Int = 4000

2015/02/13 17:24

Yang Wonsuk

흠 카운트를 숫자 제조하는 느낌으로 제조하면서 생기는 8이라는 숫자를 모조리 세어봤는데 다른분들은 엄청나시군요 ......

package count_8;

public class count8 {
    public static void main(String[] args)
    {
        int count=0;

        for(int a=0; a<1; a++){
            for(int b=0; b<=9; b++){
                for(int c=0; c<=9; c++){
                    for(int d=0; d<=9; d++){
                        for(int e=0; e<=9; e++){
                            if(e==8)
                                count++;
                            if(d==8)
                                count++;
                            if(c==8)
                                count++;
                            if(b==8)
                                count++;
                            if(a==8)
                                count++;
                        }
                    }
                }
            }
        }

        System.out.println(count);
    }
}

2015/02/19 05:18

zerofury

Python 3.4.2입니다. 기본에 충실하게 해 보았습니다.

sum8s = 0
for i in range(1,10001) :
    for j in str(i) :
        if j == '8' :
            sum8s += 1
print(sum8s)

2015/02/22 14:57

Shin Kyosoo

public class CountingEight {
    private static int count = 0; 
    public static void main(String args[]){
        for(int num = 1 ; num <= 10000; num++){
            String numStr = String.valueOf(num);
            int sl = numStr.length();
            for (int i=0; i < sl; i++){
                if ( numStr.charAt(i) == '8') count++;
            }
        }
        System.out.println("count is "+count);
    }
}

2015/02/28 01:39

주주

무식하게 풀어봤습니다

public class CD393 {
    public static void main(String[] args){
        int answer = 0;
        for(int i = 1; i <= 10000; i++){
            for(char c : new Integer(i).toString().toCharArray()){
                if(c == '8') answer++;
            }
        }
        System.out.println(answer);
    }
}

2015/02/28 19:00

오 지석

파이썬 3.2.3에서 작성했습니다.

count=0
for x in range(10000):
    for n in str(x):
        if int(n) == 8:
            count=count+1
print(str(count))

2015/03/10 15:57

임 진승

TDD로 작성해보았습니다.

public class CountEightsTest {

    // with 1 to n numbers
    // it should count the number of 8
    @Test
    public void itSouldCountTheNumberOf8() {

        CountNumbers counter = new CountNumbers('8');
        assertEquals(0, counter.countRangeFor(1,1));
        assertEquals(0, counter.countRangeFor(1,7));

        assertEquals(1, counter.countRangeFor(1,8));
        assertEquals(1, counter.countRangeFor(1,10));
        assertEquals(1, counter.countRangeFor(1,17));

        assertEquals(2, counter.countRangeFor(2,18));
        assertEquals(8+8, counter.countRangeFor(2,87));

        assertEquals(8+8+2, counter.countRangeFor(2,88));

        assertEquals(2+3, counter.countRangeFor(887,888));
        assertEquals(1+2, counter.countRangeFor(807,808));
        assertEquals(2+1, counter.countRangeFor(8008,8009));

        assertEquals(0, counter.countRangeFor(1000,1001));
    }


    class CountNumbers {
        private char character;

        public CountNumbers(String character) {
            this.character = character.toCharArray()[0];
        }
        public CountNumbers(char character) {
            this.character = character;
        }

        public int countRangeFor(int start, int end) {
            int count = 0;
            for(int i = start; i <= end; i++) {
                String number = i+"";
                int addition =countTheNumberOf(number);
                count += addition;
            }
            return count;
        }

        private int countTheNumberOf(String string) {
            int count = 0;
            for (char one : string.toCharArray()) {
                if ( one == character ) {
                    count++;
                }
            }
            return count;
        }
    }
}

2015/03/15 19:53

노광선

C#으로 작성했습니다. 7에서 9 milliseconds 정도 걸렸습니다.

using System.Linq;

        public int CountEights(int n)
        {
            var sum = 0;
            for (int i = 0; i <= n; i++)
                sum += i.ToString().Count(e => e.ToString().Contains('8'));
            return sum;
        }

2015/03/17 18:54

Straß Böhm Jäger

Using python

print str(range(1,10000)).count('8')

프로그래밍 언어를 사용하면 저렇게 구할 수 있지만 맨 앞에 답을 다신 'Jake kim'님 답변대로 생각을 얼마나 논리적으로 전개시킬 수 있나의 문제같네요 허허

2015/03/28 22:40

freeefly

c 언어입니다.

#include <stdio.h>

int main(void)
{
    int b = 10000, c = 0, Count = 0, i = 0;

    while(b >= 0)
    {
        i = b;
        while(1)
        {
            c = b%10;
            b = (int) b/10;
            if((double) c/8==1)
            {
                Count++;
            }
            if(b==0)            
                break;
        }
        b = i - 1;
    }
    printf("%d\n", Count);
    return 0;
}

2015/04/08 15:02

전승빈

Python 3.4

print(list(range(1,10001)).count('8'))

2015/04/09 01:53

Edi Slie

arr = []
for i in range(7,9999):
    arr += str(i)
sum = 0
for i in arr:
    if (int(i) == 8):
        sum += 1
print(sum)

아 count라는 함수가 존재하는군요 ㅠ

2015/04/10 17:33

박 해수

#include <stdio.h>

int main(void)
{
    int i , j , k , l;
    int n=0;
    for( i  =  0 ; i <=9 ; i++)
    {
        for( j = 0; j <= 9 ; j++)
        {
            for( k = 0 ; k <= 9 ; k++)
            {
                for( l = 0 ; l <= 9 ; l++)
                {
                    if( i == 8 )
                        n++;
                     if(j==8)
                        n++;
                    if(k==8)
                        n++;
                    if(l==8)
                        n++;
                }
            }
        }
    }

    printf("%d\n",n);
    return 0;

}

다른 분들 대단하시네요.. 얼릉 C를 끝내고 다른 언어 공부해야할듯

2015/04/15 13:35

김 성환

PHP

<?php
$count = 0; // $count를 숫자화시킨다
for($i=1;$i<=10000;$i++){ // 1부터 10000까지 반복한다
    $i = (string)$i; // $i를 문자화시킨다 (이유 : 밑의 $j번째 글자를 불러오기 위해)
    for($j=0;$j<strlen($i);$j++){ // 0부터 $i의 글자수 - 1번만큼 반복한다
        if($i[$j]=="8")$count += 1; // $i의 $j번째 글자가 8이면 $count를 +1시킨다
    }
    $i = (int)$i; //$i를 숫자화시킨다.
}
echo $count; // $count를 출력한다.
?>

PHP는 간단하게(?)되네요 ㅋㅋㅋ

2015/04/20 22:53

장 효찬

#include <iostream>
using namespace std;

int main(){
    int count = 0;
    int bcd[4] = { 0 };
    int num;

    for (int i = 1; i < 10000; i++)
    {
        num = i;
        for (int j = 3; j >= 0; j--)
        {
            bcd[j] = num % 10;
            num /= 10;
        }

        if (bcd[0] == 8)
            count++;

        if (bcd[1] == 8)
            count++;

        if (bcd[2] == 8)
            count++;

        if (bcd[3] == 8)
            count++;
    }

    cout << "8이 나온 횟수 : " << count << endl;

    return 0;
}

이렇게 짜봤습니다... 어떤가요?? 제가 생각한 방법은 예를들어 124라는 숫자를 bcd코드로 변환해서 0, 1, 2, 4로 만듭니다 그리고 각 자리의 숫자가 8이면 count를 하나 증가시키는 방법입니다

2015/04/28 01:48

정동윤

Go 로 간단히 짜봤습니다.

func main() {
    count := 0
    for i := 1; i < 10001; i++ {
        count += strings.Count(strconv.Itoa(i), "8")
    }
    fmt.Println(count)
}

2015/04/29 00:06

전 수현

Javascript 입니다.

var cnt = 0;
var strNum;
for(var i=1;i<=10000;i++) {
    strNum = String(i);
    for(var j=0;j<strNum.length;j++){
        if(strNum[j] === "8") {
            cnt++
        }
    }
}
console.log(cnt);

2015/05/06 14:33

JakartaKim

Tcl/tk입니다.

set sum 0
set match_num 0
for {set x 1} {$x <= 10000} {incr x} {
    set pattern_check [ regexp -all {[8]} $x ]
    if { $pattern_check != 0 } {
        lappend match_num   $pattern_check
    }
}
set sum [ expr [ join $match_num "+" ]]

2015/05/08 11:52

YS_SHIN

자바 한줄로 해봤습니다. 좀 지저분하네요

IntStream.range(1, 10000).filter(e -> String.valueOf(e).contains("8") ).map(e -> String.valueOf(e).replaceAll("[^8]", "").length()).sum();

2015/05/08 15:09

황진하

Python

print(str(range(10000)).count('8'))

2015/05/19 16:29

Jason Oh

{```{.cpp}

#include<iostream>

using namespace std;

int eight(int n);

int count;

int main() {
 for(int i = 0; i < 10001; i++) {  
        eight(i); 
 }
 cout << "8의 개수: " << count << endl;

 return 0;
}

int eight(int n) 
{ 
           if(n%10 == 8) 
              count++; 
           if(n > 10) 
              eight(n/10);

   return count; 
} ```

2015/05/29 11:25

이 자현

저는 좀 특이하게 ! (? ㅋㅋ)

        static void Main(string[] args)
        {
            int result = 0;
            for(int i = 1;i<= 10000;i++)
            {
                char[] value = i.ToString().ToArray();
                for(int z = 0; z<value.Length;z++)
                {
                   if(value[z] == '8')
                   {
                       result++;
                   }
                }
            }
            Console.WriteLine(result);
        }

2015/06/14 17:19

정우진

  • 수학적 풀이

0000부터 9999까지로 생각을 하면 4자리수(숫자 4개)가 10000번 반복되었으므로, 총 사용된 숫자는 4만개. 모든 정수는 동일한 빈도로 사용되었기 때문에 나누기 10 하면, 4000

  • 문자열 모두 합친 후, 문자열 메소드 중 count 사용
print ''.join([str(i) for i in range(1,10000)]).count('8')
  • 정규식(count가 익숙하지 않을 경우)
import re

pat=re.compile('8')
n=''.join([str(i) for i in range(1,10000)])
s=len(pat.findall(n))
print s

2015/06/15 01:58

NoelBird

using java

public class Main {

  public static void main(String[] args) {
    int returns = 0;

    for(int i = 0; i<10000; i++)
    {
         String str = String.valueOf(i);
        for(int j = 0; j<str.length(); j++)
           returns += ("8".equals(String.valueOf(str.charAt(j))))? 1:0;
    }

    System.out.println(returns);

    }
}

2015/06/16 18:27

문성훈

#include <stdio.h>
#include <Windows.h>

int main()
{
    int sum=0;

    for(int i=1;i<10001;i++)
    {
        for(int j=i;j>0;j/=10)
        {

            if(j%10 == 8)
            {
                sum++;
            }
        }

    }
    printf("%d",sum);
    system("pause");
    return TRUE;
}

2015/06/17 11:38

심 기용

number_list = ""
for i in range(1,10000):
        number_list = number_list + str(i)
print (number_list.count('8'))   

2015/06/18 23:14

Jethro

public class dojo2

{

  public static void main(String[] args)

  {

    //count from 0 - 10000

    int count = 0 ;

    for(int i = 0 ; i<10001 ; i++){

      String s = Integer.toString(i);

      char[] a = s.toCharArray();

      for(int j=0;j<a.length;j++){

        if(a[j] == '8')

        {

         count++;

        }

      }

    }

    System.out.println("Result: "+count);

  }

}


2015/06/20 12:30

전 진혁

total_count_8 = 0

for number in range (1, 10001):
    total_count_8 += str(number).count('8')

print total_count_8

4000

2015/06/21 03:39

슬로씽킹

static void Main(string[] args)
        {
            Console.WriteLine(Answer(8,10000));
        }

static int Answer(int findNum,int numMax)
        {
            string sum = "";

            for (int i = 1; i <= numMax ; i++)
            {
                sum += i;
            }

            int answer = sum.Length - sum.Replace(findNum.ToString(), "").Length;

            return answer;

        }

2015/06/22 18:33

허 빈

자바

일단 반복문으로 1부터10000까지 범위를 잡고 일의자리숫자 십의자리숫자 백의자리숫자 천의자리숫자를 따로 분리한후 분리한숫자를 8로 나눳을경우 0이나오면 카운트를 1씩증가시키는식으로 짜봤습니다

package dojavn;
public class dsa {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int count=0;
        for(int i=1;i<10000;i++){

            int x1=i/1000%10;
            int x2=i/100%10;
            int x3=i/10%10;
            int x4=i/1%10;
            if(x1==8){count++;}
            if(x2==8){count++;}
            if(x3==8){count++;}
            if(x4==8){count++;}

        }

        System.out.println(count);
    }

}

2015/07/03 06:32

사석훈

#include <stdio.h>
int main()
{
    int a=0,b=0,c,i;
    for(i=1;i<=10000;i++)
    {
        c=i;
        for(;;)
        {
            if(b==8)a++;
            b=c%10;
            c/=10;
            if(c==0)break;
        }
    }
    printf("%d",a);
}

2015/07/15 22:54

코딩호빵이

흠... 힘드네요... 초보라 그런지..ㅠㅠ - 코딩호빵이, 2015/08/22 18:38

    public static int count(int number){
        int count = 0  ;

        for(int i= 1 ; i <=number ; i++){
            String temp = i+"";
            String[] temp2 = temp.split("");

            for( int j = 0 ; j < temp2.length ; j++){
                System.out.println(temp2[j]);
                if(temp2[j].equals("8")){
                    count++ ;
                }
            }
        }
        return count;
    }

2015/07/28 13:31

seonghyun

void exce7()
{
    int count = 0;
    for (int i = 0; i <= 10000; i++)
    {
        int temp = i;
        while (temp > 0)
        {
            if (temp % 10 == 8)
                count++;
            temp /= 10;
        }
    }

    printf("1에서 10000까지 8의 갯수는 %d개\n", count);
}

2015/08/13 12:41

조서현


def eightcounter(a):
    tmp = 0
    a = str(a)
    for i in range(0, len(a)):
        if int(a[i]) == 8:
            tmp = tmp + 1
    return tmp

summ = 0
for ii in range(0, 10000):
    summ = summ + eightcounter(ii)

print(summ)

깊은 생각 없이 단순 코딩을 하고 있었는데...창의적 해법에 반성하게 되네요.

2015/09/13 22:51

박재우

a = 0
for i in range(10000):
    a += str(i).count('8')
print(a)

1일 1문제 파이팅

2015/10/24 23:43

뻬이스북

저는 무식하게 for문과 string으로 하는걸 시도해 봤습니다. count method 없이 만들었습니다.

entire_string=""
eights=0
for i in range(1,10001):
    entire_string=entire_string+(str(i))
number_list=list(entire_string)

for j in number_list:
    if j=="8":      
        eights=eights+1
    else:
        continue
print eights

2015/11/05 22:46

Choi Hyen-soo

0000부터 9999라고 생각하고 4자리숫자가 10000개이므로 들어가는 숫자의개수는 4만개 0부터 9까지 10개의 숫자가 같은 비율로 들어가니 4만을 10으로 나누면 4천!

2015/11/12 01:52

땅콩2

python3입니다. 각 숫자를 문자로 바꾼다음 8을 1로, 다른건 0으로 바꾸고 다 더하였습니다. 다른분들 푸신걸 보니 제가 바보같았네요 ㅜㅠ

print (sum([sum(map(lambda x: (1 if x == '8' else 0), s)) for s in [str(n) for n in range(1, 10001)]]))

2015/11/19 17:01

jspark

<?php
    $cnt = 0;

    for ($i=0; $i <= 10000; $i++) { 
        $temp = explode('8', (string)$i);
        $cnt = $cnt + (count($temp) -1);
    }

    echo $cnt;

?>

좀 야매스러운방법이긴 하지만 생각해봣습니다.

2015/11/24 16:40

한기우

#include <iostream>

using namespace std;




int main()
{
    int total = 0;

    for (int i = 0; i <= 10000; ++i)
    {
        for (int d = 10; d <= 10000; d *= 10)
        {
            if (i%d / (d / 10) == 8)
                ++total;
        }
    }

    cout << total << endl;


    return 0;
}

이미 완벽한 답이 나왔으니 전 컴퓨터를 학대하는 방법으로!

2015/12/27 14:26

신 동현

#PYTHON 3.5
print(str(list(range(0,10001))).count('8'))

2015/12/29 15:47

. anisky07

lst = []
for i in range(1,10001):
    lst.append(i)
result = 0
lst_str = str(lst)
for i in lst_str:
    if i == "8":
        result += 1
print result

스트링으로 받아서 8을 다 셌습니다. 그냥 머리로 푸신 분들도 계시네요.

2016/01/05 16:00

취미로재미로

  • python 으로 작성하였습니다.
cnt=0
for i in range(1,10001):
    for a in str(i):
        if int(a)==8:
            cnt+=1
print cnt

2016/01/08 08:51

씨니컬우기님

Swift 2.1 입니다.

비싼 String 연산을 쓰지않도록 고민해봤습니다.

    var count = 0

    for i in 1...10000 {
        var number = i
        while number > 0 {
            count += ((number % 10) == 8) ? 1 : 0
            number = number / 10
        }
    }

    return count

간단하게는 아래와 같이도 할 수 있겠네요

Range(start: 1, end: 10001).reduce(0) { $0 + String($1).characters.filter { $0 == "8" }.count }

2016/01/12 10:52

rainris

python 3.4

count8 = 0
for i in range(10000):
    int2list = list(str(i))
    count8 += int2list.count('8')

print(count8)

2016/01/13 17:54

김 민성

print sum(str(n).count('8') for n in range(1,10000))

2016/01/16 15:50

상파

python

print(sum([str(i).count('8') for i in range(1,10001)]))

haskell

sum $ map (\n->foldr (\x acc->if x == '8' then acc + 1 else acc) 0 (show n)) [1..10000]

c++

#include <stdio.h>

int main() {
    int n = 0;
    char szNum[4];
    for(int i=1;i<10000;++i) {      
        sprintf(szNum, "%04d", i);
        for(int j=0; j<4; ++j) {
            if(szNum[j] == '8') {
                n += 1;
            }
        }       
    }
    printf("%d", n);
    return 0;
}

결과 4000

2016/01/28 21:50

윤태호

Ruby

# one-liner
p ([*1..10000]*'').count '8' #=>4000
# for test
counter = ->num,s {([*1..num]*'').count s}

Test

expect(counter[10000,'8']).to eq 4000

2016/02/14 12:48

rk

java로 줄여보고 싶었습니다...

public class eight {
    public static void main(String... args){
        int count = 0;
        for(int i = 0 ; i<=10000 ; i++)
            count += (" "+i+" ").split("8").length-1; // 배열의 길이로 측정
                //split과정에서 8이 끝에 있으면 배열 길이로 계산되지 않으므로 문자열 추가
        System.out.println(count);
    }
}

2016/02/24 20:28

Alias

i=1
result=0
while i<=10000:
    data=list(str(i))
    result+=data.count('8')
    i+=1
print(result)

Python 3.3

2016/02/25 18:34

lovegalois2

var totalCount = 0
        for i in 0..<10000{
            let str = String.init(format: "%4d", i)
            for ch in str.characters {
                if ch == "8" {
                    ++totalCount
                }
            }
        }

        print("total \(totalCount)")

2016/02/28 14:44

한자리 숫자에서 8의 갯수는 1가지.
두자리 숫자에서 8의 갯수는 1*10(십의 자리가 8인 경우) + 9*1(일의 자리가 8인 경우) = 10+9 = 19가지.
비슷한 방법으로, 세자리 숫자에서 8의 갯수는 1*10*10 + 9*1*10 + 9*10*1 = 100+90+90 = 280.
마지막으로, 네자리 숫자에서 8의 갯수는 1*10*10*10 + 9*1*10*10 + 9*10*1*10 + 9*10*10*1 = 1000+2700 = 3700.
따라서, 총합을 구하면 1+19+280+3700 = 4000개.

2016/03/01 13:34

Gtae

print(sum(str(x).count('8') for x in range(10001)))

파이썬 3.5.1

public class Count_8 {
    public static final int TARGET = 10000;
    public static void main(String[] args) {
        int i = 1;
        int[] result = new int[10];
        while (true){
            String s = ""+i;
            for(int j = 0; j < s.length(); j++){
                result[Integer.parseInt(""+(s.charAt(j)))] += 1;
            }
            i++;
            if (i>=TARGET)
                break;
        }
        System.out.println(result[8-1]);
    }

}

자바

답은 4000

2016/03/12 17:16

Flair Sizz

1~9999 까지 중 첫째자리가 8인 경우 : 나머지 세자리에 0부터 999까지의 수가 올 수 있으므로 총 1000가지 둘째, 셋째, 넷째 자리도 위의 경우와 동일하므로 1000 * 4 = 4000가지

2016/03/13 04:04

mozzi

파이썬3.4입니다

s = 0
for i in map(str, range(1, 10001)):
    s += i.count('8')
print(s)

2016/03/21 11:58

디디

풀었긴했으나 올리기는 민망

2016/03/23 15:42

[email protected]

Python 2.7

print sum([str(n).count('8') for n in xrange(1,10001)])

2016/03/24 11:05

최 재민

파이썬 3.4.2

s = ''
for i in range(1,10001):
    s += str(i)
print(s.count('8'))

2016/04/02 16:15

차우정

count=0
for i in range(1,10001):
    for j in str(i):
        if j=="8":
            count+=1
print(count)

파이썬 아직 반복문 까지 밖에 몰라서.. 내장 함수도 잘 몰라요.

2016/04/21 00:19

Dr.Choi

sum = 0
for i in range(1,10001):
    a = []
    i = str(i)
    for k in range(len(i)):     
        a.append(i[k])      
    sum  += a.count('8')
print(sum)

답은 4000

2016/04/26 12:05

Lee Sung Hyun

JAVA 다음에는 저도 창의적인 방법으로 풀어보려고 노력해 볼께요~ 지저분하지만 올립니다 :)

public class Goolgle_num8 {

    static public void main(String arg[]) {
        Integer num;
        int count = 0;
        String N = "8" ;
        for (int i = 1; i <= 10000; i++) {
            num = i;

            for (int j = 0; j < num.toString().length(); j++) {
                System.out.println( num.toString().charAt(j)  );

                if (num.toString().charAt(j) == N.charAt(0) ) {
                    count++;
                }
            }

        }
        System.out.println( "the count of 8 from 1 to 10000 : " + count );
    }

}

2016/04/30 21:29

brad.choi

  • 1의 자리 : 10을 주기로 등장. 한번에 1개씩 등장.
  • 10의 자리 : 100을 간격으로 반복적으로 등장하지만 10개가 뭉치로 등장.
  • 100의 자리 : 1000을 간격으로 반복적으로 등장하지만 100개가 뭉치로 등장.
  • 1000의 자리 : 10000을 주기로 등장. 1000개가 뭉치로 등장.

결국 모든 자리에서 1000개씩 등장하네요.

python 코드로 보면

def countDigitInRange(beg, end, digit):
    return sum([str(x).count(str(digit)) for x in range(beg, end)])

print countDigitInRange(1,10000,8)
$ 4000

2016/05/07 10:26

LEE JaeJun

Python 3.4.4

print(sum([str(i).count("8") for i in range(1, 10001)]))

2016/05/10 11:27

SanghoSeo

length(unlist(gregexpr(8, grep(8, c(1:10000), value = T))))

R 코드 입니다. 감사합니다.

2016/05/18 15:48

Byun Seongjun 변성준

print( sum( [ str(i).count('8') for i in range(10000) ] ))

2016/05/19 14:20

choo dg

>>> "".join(str(x) for x in range(1,10001)).count('8')
4000

2016/05/26 11:19

Park Ohyoung

값을 출력하기위해서는 앞에 print(작성하신 코드)가 빠진 것 같습니다. - greatfarmer, 2016/05/28 00:49
+1 Python console에서는 변수에 대입하지 않으면 바로 출력됩니다. - Park Ohyoung, 2016/05/31 10:22

파이썬 3.5로 작성되었습니다.

sum = 0
for i in range(10001):
    sum += str(i).count('8')

print(sum)

굉장히 직관적으로 풀었습니다.

숫자 1~10,000까지 문자로 바꾸고 '8'을 카운터하는 방법으로 풀었습니다.

부족한 점이 많습니다. 감사합니다.

2016/05/28 00:37

greatfarmer

#include <iostream> 
#include <string> 
#include <sstream> 
using namespace std;

// 10000까지밖에 없다는 점에서 그냥 
// brute force로도 빨리 해결가능. 

string toString(int n){
    stringstream ss; 
    ss << n; 
    return ss.str(); 
}

int main(){
    int cnt = 0;  
    for (int i = 1; i <= 10000; i++){
        string s = toString(i); 
        for (int j = 0; j < s.size(); j++){
            if (s[j] == '8') ++cnt; 
        }
    }
    cout << cnt << endl;
    return 0; 
}
brute force code

2016/05/28 20:57

iljimae

PHP 함수로 풀어봤어요 ㅎ

$sum = 0;
for($i=1; $i<=10000; $i++) {
    $str = array_count_values(str_split((string)$i));
    $sum += $str[8];
}
echo $sum;

2016/06/03 02:50

허큐리

#include <stdio.h>

int main(void)
{
    int i, temp, count;
    count = 0;

    for (i = 1; i < 10001; i++) {
        temp = i;
        while (i >= 10) {
            if (i % 10 == 8) {
                count++;
                i /= 10;
            }
            else {
                i /= 10;
                continue;
            }
        }
        if (i == 8)
            count++;
        i = temp;
    }
    printf("1 ~ 10000까지 8이라는 숫자가 나오는 횟수: %d\n", count);
    return 0;
}

C언어로 작성했습니다. 좀 더 단순하게 짜고싶은데.. 연습 좀 해야겠습니다. ㅎㅎ

2016/06/03 18:24

GyuHo Han

package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    count := 0
    for i := 1; i <= 10000; i++ {
        count += strings.Count(strconv.Itoa(i), "8")
    }

    fmt.Print(count)
}

2016/06/11 23:28

uuuuuup

int box[] = new int[10];//각 숫자를 저장할 공간
        for (int i = 1; i <= 10000; i++) {
            box[i%10]++;//일의 자리
            if (i>=10)  box[i/10%10]++;//십의 자리
            if (i>=100) box[i/100%10]++;//백의 자리
            if (i>=1000) box[i/1000%10]++;//천의 자리
            if (i==10000) box[i/1000%10]++;//천의 자리
        }
        System.out.println(box[8]);

2016/06/16 21:26

김 수영

GCC

a;
j;
main(i){
for(;i<10001;j?j%10-8||a++,j/=10:(j=++i));
printf("%d",a);
}

2016/06/25 13:45

Lotion

#include <iostream>

int main(void)
{
    int count = 0;
    for (int i = 0; i < 10000; i++) {
        for (int j = i; j > 0; j /= 10) {
            if (j % 10 == 8)
                count++;
        }
    }
    std::cout << count << std::endl;
    return 0;
}

4000이 나오네요

2016/06/26 15:00

rev

eightCount = 0

for n in range(1, 10001) : 
    while n > 0 :
        if n % 10 == 8 :
            eightCount = eightCount +1
        n = n // 10

2016/06/26 23:06

안 동환

아.. 단순히 갯수만 카운팅 하면 되는거였군요

저는 8888 갯수 4개 이런식로 다 찍으라는 말인줄 알고...
8이 들어가는 것 마다 다찍어 내고 총 갯수도 나오게 했네요 역시 문제를 재대로 보는 능력부터 길러야 겟어요 ㅜㅜ ```{.java}

public static void main(String[] args) {

    final int  MAX =10000;
    int number_8_conut=0;
    int total_number_8_count=0;

    for(int i =0; i<=MAX; i++){

        String AllNumber = String.valueOf(i);

        if(AllNumber.contains("8")){
            for(int j=1;j<=AllNumber.length();j++){

                if (AllNumber.charAt(j-1)=='8') {
                    number_8_conut +=1;
                    total_number_8_count +=1;
                }
            }
            System.out.println(AllNumber+"   갯수 :"+number_8_conut+"입니다. ");
            number_8_conut=0;
        }   
    }
    System.out.println("8의 총 갯수는 :"+total_number_8_count+"개 입니다.");         
}

```

2016/06/29 03:46

남 철진

0~9 : 1개 0~99: 1 * 10 + 110 =20 0~999: (1 * 10 + 110) * 10 + 100 = 300 // 자릿수 개수 * 10^(자릿수-1) n*10^(n-1) : n = 4 => 4000개

2016/07/06 18:17

강 경수

def eight(n):
    nstring=str(n)
    nlist=[]
    for k in range(0, len(nstring)):
        nlist.append(nstring[k])
    #print(nlist)
    return nlist.count('8')

result=0
for k in range(1, 10001):
    result+=eight(k)
print(result)

별해) 8의 개수와 상관 없으므로 10000을 0000으로 보아서, 범위를 0000~9999로 생각해도 무방함. 0000 0001 0002 ... 9999 까지 4*10000 매트릭스에 늘여쓰면 모두 40000개의 숫자가 쓰임. 이 때, 수의 분포는 '균질적'이므로 0~9까지 쓰인 숫자의 개수는 똑같음. 따라서 40000/10=4000

2016/07/13 23:04

최승호

#Google Problem My Code.py

result = 0

for i in range(10000):
    for j in str(i):
        if j == '8':
            result+=1
print(result)

단순하게 코드로만 풀어야지 생각하고 있었는데 Best 댓글을 보니까 감탄이 나오네요

2016/07/15 14:38

지 정한

C++로 코딩했습니다.

#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
    int count = 0;

    for (int i = 1; i <= 10000; ++i)
    {
        char temp[6] = {0};
        sprintf(temp, "%d", i);

        for (int j = 0; j < strlen(temp); ++j)
        {
            if (temp[j] == '8')
                count++;
        }
    }

    cout << count << '\n';

    return 0;
}

2016/07/22 12:28

손 량

print str(range(1,10001)).count('8')

2016/07/28 11:22

Kim Heeseok

int count=0;
        for(int w = 0 ; w<10 ; w++){
            for (int q = 0; q < 10; q++) {
                for (int o = 0; o < 10; o++) { // 십자리
                    for (int k = 0; k < 10; k++) { // 십자리
                        if (w == 8)
                            count++;
                        if (q == 8)
                            count++;
                        if (o == 8)
                            count++;
                        if (k == 8)
                            count++;
                    }
                }
            }
        }
        System.out.println(count);


    }//main
}

2016/07/29 13:34

김치영

파이썬으로 해봤습니다.

su = 0

for x in range(1,10001):
    a = str(x)
    b = a.count('8')
        su += b


print(su)

1부터 10000까지 숫자를 하나씩 문자열로 바꾸고, 그 문자열에서 '8'이라는 문자를 찾아 세는 코드입니다. 답은 4000!!

2016/08/16 17:35

lkungs

#def_name : count_8 / input : start, last / output : couting of 8 / type of result : number
# what do i need to solve this problem?
# split every numbers into one number
# and check whether it is 8 or not

def count_8(start,last):
    count = 0
    for num1 in range(start,last+1):
        if len(str(num1)) == 1 and num1 == 8:
            count += 1
        else:
            for num2 in str(num1):
                if str(num2) == '8':
                    count += 1
    return count

print count_8(1,10000)   # result : 4000



2016/08/21 23:59

kim SeongHyeon

print str(range(1,10001)).count("8")

코드 결과는 4000 나왔습니다.

이론적으로는 각 자리의 숫자를 그룹이라고 생각해서 한 자리씩 카운팅 하면 될것같습니다. 천의 자리에 8이 있을 때를 그룹a ... 일의 자리에 8이 있을 때를 그룹d라고 생각하면 각 그룹에 남는 숫자칸이 3칸이고 각 숫자칸에 0~9 (10)개가 들어갈 수 있으니 경우의 수가 101010 = 1000으로 각 그룹당 1000개의 경우가 있으므로 1000*4 = 4000이 되는것 같습니다.

2016/08/22 03:49

sega

python 2.7

count=0
for i in str(range(0,10000)):
    if(i=='8'):
        count+=1

print count 

2016/08/23 19:01

leye195

int solution()
{
    int k=0,j=0,iCnt=0,iSum=0;
    char byTmp[8];

    for(k=0; k<10000; k++)
    {   
        iCnt=0;     
        memset(byTmp, 0x00, sizeof(byTmp));
        sprintf(byTmp, "%d",k);

        for(j=0; j<strlen(byTmp); j++)
        {
            if(byTmp[j] == '8')
                iCnt++;
        }
        iSum += iCnt;
    }
    printf("result : [%d]\n",iSum);
    return 1;
}

result : [4000]

구글이라 그래서 창의력을 요구할 줄 알았는데, 그냥 기초적인 단순한 문제였네요..

2016/08/24 17:41

siso

public void CountEIGHTOneToTenThousand()
        {

            int cnt9 = 0;

            for (int i = 1; i <= 10000; i++)
            {
                string Num = Convert.ToString(i);
                foreach (char num in Num)
                {
                    if (num == '9')
                        cnt9++;

                }
            }
            Console.WriteLine(cnt9);



        } 



비슷한 문제가 하나 있었는데, 그 코드를 재활용한겁니다

2016/08/29 01:29

이규민

include

int main(void){ int count=0; int i,temp;

for(i=1;i<=10000;i++){
    for(temp=i;;){
        (temp%10==8)&&count++;
        if(temp/10==0)break;
        else temp/=10;
    }
}
printf("%d", count);

}

2016/08/30 22:31

kawa1lg1rl

ruby 2.3

puts (1..10001).to_a.to_s.count("8")

result

4000

2016/09/04 15:42

happygrammer

Javascript ES6 style 로 풀어봤습니다. loop 돌리는거 싫어해서... pure function으로 짰습니다.

function countEight (number) {
  let array = Array.from(new Array(number), (x,i) => i + 1)
  return array.join("").split("8").length-1;
}

2016/09/09 07:36

Hur Harry

#include <stdio.h>
#include <stdlib.h>

void main(void) {
    int count = 0;
    int size = 0;
    for(int i = 0 ; i < 10000 ; i++) { 
        if(i / 1000 == 8)
            count++;

        if((i%1000 / 100) == 8)
            count++;

        if(((i%1000)%100 / 10) == 8)
            count++;

        if((((i%1000)%100)%10) == 8)
            count++;
    }

    printf("%d\t", count);
}

2016/09/12 16:40

코딩초보

(0 to 10000).map(_.toString.count(_ =='8')).sum

스칼라에서 map을 이용해 간단하게 풀어봤습니다.

2016/09/13 10:44

김카프

Array.apply( null, Array( 10000 ) ).map( ( v, i ) => { return i } ).join( "" ).match( /8/g ).length

Javascript로 파이썬처럼 짜봤습니다.

파이썬하고 루비 코드가 멋있네요 ㅎ

2016/09/14 04:08

Gihwan

다들 정말로 대단하시네요.. 여기서 count도 배우고, 신기한 아이디어들도 얻고 갑니다. 감사합니다.

#1부터 10,000까지 8이라는 숫자가 몇 번 나오는가?
a = list(range(1,10001))
b = ""
for i in a:
    b += str(i)
c = 0
for i in b:
    if eval(i) == 8:
        c += 1
    else:pass
print(c)

2016/09/17 15:00

신 명진

i=1
k="8888"
sum=0
while i < 10000:
   j = str(i).zfill(4)
   cn1 = int(not bool(int(j[0])  ^ int(k[0])))
   cn2 = int(not bool(int(j[1])  ^ int(k[1])))
   cn3 = int(not bool(int(j[2])  ^ int(k[2])))
   cn4 = int(not bool(int(j[3])  ^ int(k[3])))
   sum = sum + cn1 + cn2 + cn3 + cn4
   i=i+1

print(sum)

2016/09/24 21:01

제 원

Java 풀이


public class Google {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int n = 10000;
        int result = 0;
        for(int i = 1; i <= n; i++){
            result += countEight(i);
        }

        System.out.println(result);
    }

    public static int countEight(int num){
        int cnt = 0;
        while(true){
            cnt += (num % 10 == 8) ? 1 : 0;
            if(num / 10 == 0){
                break;
            }
            num = num / 10;
        }

        return cnt;
    }

}

2016/10/07 23:57

이 정현

#define _CRT_SECURE_NO_WARNINGS

#include <windows.h>
#include <stdio.h>
#include <algorithm>
using namespace std;

int main(void) {
    int n, count =0;
    for (int i = 1; i < 10000; i++) {
        n = i;
        while (n) {
            if (n % 10 == 8) {
                count++;
            }
            n = n / 10;
        }
    }
    printf("num 8 : %d\n", count);
    system("pause");
    return 0;

}

2016/10/08 10:31

개허접

파이썬

print(str(list(range(1,10001))).count('8'))

2016/10/19 08:33

훠니

c언어로 작성했어요```{.c}

include

int main() { int arr[5] = { 0, }; int j, count = 0, i = 10001;

while (i--)
{
    arr[4] += 1;
    j = 5;
    while (j--)
    {
        if (arr[j] == 10)
        {
            arr[j - 1] += 1;
            arr[j] = 0;
        }
        if (arr[j] == 8)
        {
            count++;
        }
    }
}
printf("%d", count);

} ```

2016/10/22 12:20

Kim Jisoo

a=0
for i in range(10000):
    x=str(i)
    for j in x:
        if j=='8':
            a+=1
print(a)

2016/10/29 12:34

ㅇㅇㅅ

numbers = range(0,10000)
eights = []

for i in numbers:
    if '8' in list(str(i)):
        result = list(str(i)).count('8')
        eights.append(result)

print(sum(eights))

Python 3.5.2

2016/10/29 18:37

Kim J.S.

public class question { public static void main(String[] args) {

    int segi = 0;

    for (int i = 1 ; i <= 10000 ; i++)
    {

        String num_c = ""+i;
        for (int j = 0 ; j <= num_c.length() ; j++)
        {
            if ((int)(i/Math.pow(10, j))%10 == 8)
            {
                segi++;
                System.out.println(i);
            }
        }
    }
    System.out.println(segi);

}

}

//java

2016/10/29 19:59

정 다솔

Java

System.out.println(IntStream.rangeClosed(1, 10000).map(i -> (int)String.valueOf(i).chars().filter(j->j=='8').count()).sum());

4000

2016/10/30 22:51

compert

N을 10으로 나누면서 나머지 8을 체크하는 방식입니다.

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class CountNumberEight {

    public static void main(final String[] args) {
    }

    public int countNumberEight(final int n) {
        int count = 0;

        for(int i = 1; i <= 10000; i++) {
            for(int j = i; j > 0; j /= 10) {
                if(j % 10 == 8)
                    count++;
            }
        }

        return count;
    }

    @Test
    public void testCountNumberEight() {
        assertEquals(400, countNumberEight(10000));
    }
}

2016/11/03 14:03

한비타

문제의 설명을 그대로 옮겨적는.. brute force ! :-)

1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?

int sum = 0;
for (int i = 1; i <= 10000; i++) {
  sum += count8(i);
}
return sum;

8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.

int count8(int n) {
  int count = 0;
  while (n > 0) {
    if (n % 10 == 8) {
      count++;
    }
    n /= 10;
  }
  return count;
}

2016/11/03 21:13

Han Jooyung

public class Google1 {
    public static void main(String[] args) {
        char num[] = new char [4];
        int cnt = 0;
        for(char i='0'; i<='9'; i++){ 
            num[0]=i; 
            for(char j='0'; j<='9'; j++){ 
                num[1]=j; 
                for(char k='0'; k<='9'; k++){ 
                    num[2]=k; 
                    for(char m='0'; m<='9'; m++){ 
                        num[3]=m; 
                        if(i=='8'){cnt ++;}
                        if(j=='8'){cnt ++;}
                        if(k=='8'){cnt ++;}
                        if(m=='8'){cnt ++;}
                    }
                }
            }
        }
        System.out.println(cnt);
    }
}

가장 원시적인 방법으로 풀었습니다.. 메모리 엄청 잡아먹겠네요.. 다른 방법으로도 풀어보겠습니다..

2016/11/07 13:46

Han Da Bin

메모리는 거의 잡아먹지 않을 것 같은데요? - Han Jooyung, 2016/11/10 10:03
//java
int count=0;
for(int i=0;i<10000;i++){
    if(i%10==8)count++;
    if(i/10%10==8)count++;
    if(i/100%10==8)count++;
    if(i/1000%10==8)count++;
}
System.out.println(count);

2016/11/10 16:38

Cho Wonwung

var cnt = 0;
var arr;

for(i=0;i<10000;i++) //만번동안
{
    arr = i.toString().split('8');    //숫자를 문자로 바꾼다음 8을 기준으로 토막을 칩니다.

    if(arr.length > 1){               //토막친 배열의 길이를 봅니다. 토막칠게 없으면 1입니다.
        cnt = cnt + (arr.length - 1); //토막친다음 1 뺀 것이 8의 갯수이므로, cnt 변수에 담습니다.
    }
}

alert(cnt);

javascript 소스를 그냥 올렸더니 바로 XSS 되버리네요. 게시판 올릴때 특수문자 이스케이핑 처리 해야할것 같아요

2016/11/11 09:55

구 자경

#include <stdio.h>
#include <string.h>

int found_eight_num(int num);

int main()
{
    int i=0;
    int total_cnt=0;;

    for(i=0; i<10000;i++)
    {
        total_cnt += found_eight_num(i);
    }
    printf("Total Cnt : %d\r\n",total_cnt);
}

int found_eight_num(int num)
{
    char temp_num[5];
    int str_len,ret_cnt=0;

    sprintf(temp_num,"%d",num);
    str_len = strlen(temp_num);

    for(int i=0;i<str_len;i++)
    {
        if(temp_num[i] == '8')  ret_cnt++;
    }

    return ret_cnt;
}

2016/11/14 14:20

곽 동은


counter = 0
for i in range(1, 10001):
    for digit in str(i):
        if digit is '8' : 
            counter += 1
print counter

2016/11/14 21:23

바바

/ JAVA 로 작성했습니다. / -- 그린구름님의 재귀호출 코드에 비하면 효율이 많이 떨어지네요. ^^

public class CountNumber {

    public static void main(String[] args) {

        int startNum = 1;
        int endNum = 10000;
        int num = 8;

        long lStartTime = System.currentTimeMillis();
        int retCnt = countNumber(startNum, endNum, num);
        long lDuration = System.currentTimeMillis() - lStartTime;
        System.out.println(String.format("Elapsed Time: %.3f seconds", lDuration/ 1000.0f));
        System.out.println(String.format("%d ~ %d -> %d(Counting:%d)", startNum, endNum, num, retCnt));

    }  

    /**
     * 인자로 입력받은 시작, 종료숫자 내에 세번째 인자의 숫자가 몇개 들어있는지 카운트 
     */
    public static int countNumber(int startNum, int endNum, int number) {

        int retCnt = 0;
        String num = String.valueOf(number);
        String n = "";

        for (int i = startNum; i < endNum; i++) {
            n = String.valueOf(i);

            while (n.indexOf(num) >= 0) {
                retCnt++;
                n = n.substring(n.indexOf(num)+1);
            }
        }

        return retCnt;
    }

}

2016/11/15 14:42

Lee Kyounghee

안녕하세요 처음 가입한 신참입니다. 숫자를 문자로 바꾸면 9876 => "9876" 되고 "9876" 은 [9],[8],[7],[6] 가 저장된 배열입니다. (자바스크립트에선 그렇습니다.) 각 숫자를 문자로 바꾼후 0부터 배열방 번호를 참조, 방의 내용이 "8"과 같으면 sumNum 을 1씩 올려 줍니다.


var sumNum = 0;

for (var i = 0; i < 10000; i++) {
    var tmp =i.toString();         

    for(var j =0; j<tmp.length; j++){
        if(tmp[j]=="8"){              
            sumNum++;
        }
    }
}

console.log(sumNum);     // 결과로 4000 이 나옵니다.  

2016/11/17 18:20

Chung Ho Suk

def f(n):
    li = []
    li.append(int(n/10000))
    li.append(int(n/1000)-10*int(n/10000))
    li.append(int(n/100)-10*int(n/1000))
    li.append(int(n/10)-10*int(n/100))
    li.append(n%10)
    return li

a = 0
for i in range(1, 10001):
    a += f(i).count(8)

print('10000까지 8의 개수:  %s' % (a))

2016/11/19 21:49

fdn

public class Practice {
    public static void main(String[] args) {
        int cnt=0;
        for(int i=1;i<=10000;i++){
            String str=Integer.toString(i);
            char[] c=str.toCharArray();
            for(int j=0;j<c.length;j++){
                if(c[j]=='8') cnt++;
            }
        }
        System.out.println(cnt);
    }
}

자바로 풀어봤습니다 ㅎㅎ 재밌네요~

2016/11/24 01:10

이 대균

int Count = 0; for(int i = 1;i<=10000;i++) { char[] number = i.ToString().ToCharArray();

            for (int k = 0; k < (i.ToString().Length) ; k++)
            {
                if (number[k] == "8".ToCharArray()[0])
                {
                    Count++;
                }
            }
        }

밖에 생각이..

2016/11/24 23:14

Choco

print(str(list(range(1, 100001))).count('8'))

Python 3.5.2에서 작성하였습니다.

2016/11/29 16:08

Yeo HyungGoo

print(sum([1 for i in range(1,10001) for j in str(i) if j == '8']))

#### 2016.12.04 D-445 ####

다들 정말 대단하네요.. ㅠㅠㅠ

2016/12/04 22:48

GunBang

MATLAB으로 작성하였습니다.

length(strfind(int2str([1:10000]), '8'))

답 = 4,000

2016/12/07 18:06

조현우

heleow```{.python}

```

2016/12/13 00:57

Kim Lisa

public class EightCounter {

private static int totalCount = 0;

public static void main(String[] args) {

    for (int i = 1; i <= 10000; i++) {
        countEight(i);
    }

    System.out.println(totalCount);
}

public static void countEight(int maxNumber) {

    if (maxNumber % 10 == 8) {
        totalCount++;
    }

    if (maxNumber > 10) {
        countEight(maxNumber / 10);
    }

}

}

2016/12/13 23:27

Sung Ki Bong

if name == "main":

strTotal = ''
for ii in range(1, 10000): 
    strTotal = strTotal + str(ii)

print (strTotal.count('8'))

2016/12/14 14:43

public class Ex_7 {
    public static void main(String[] args) {
        Eight e = new Eight();
        e.count();
    }
}

class Eight{
    void count(){
        int count = 0;
        for (int i = 1; i <=10000; i++) {
            int num = i;
            if (num%10==8) {
                count++;
            }
            while(num>10){
                num = num/10;
                if (num%10==8) {
                    count++;
                }   
            }
        }

        System.out.println(count);
    }
}

2016/12/15 23:03

bbubbush

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int sum = 0;
        for(int i=1; i<=10000; i++){
            int num = i;

            while(num!=0){
                if(num%10 == 8)
                    sum += 1;
                num /= 10;
            }
        }
        System.out.println(sum);
    }
}

2016/12/16 15:24

박소정

public class Eight {
    static int count = 0;
    public static void main(String[] args) {
        IntStream.rangeClosed(1, 10000).forEach(num -> {
            String.valueOf(num).codePoints().forEach(number -> { if(number - 48 == 8) count++; });
        });
        System.out.println(count);
    }
}

자바입니다. 결과 >> 4000

2016/12/21 16:32

Eunjung Ji

include

int count8(int n) { if (n == 1) return 0; int cnt = 0, tmp = n; while (tmp > 0) { if (tmp%10 == 8) cnt++; tmp /= 10; } return count8(n-1) + cnt; }

int main() { printf("%d\n", count8(10000)); return 0; }

2016/12/21 23:12

리코둔

A = 0
a = range(1,10001)
for i in a:
    for j in str(i):
        if j == '8':
            A += 1
print(A)

2016/12/23 10:13

최정진

/*
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?

8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
 */

import java.util.*;

public class Algorithm1 {

    public static Scanner sScan = new Scanner(System.in);


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String sInput = "";
        int nMax = 0, nMin = 0, nMok = 0, nCount = 0;

        sInput = sScan.nextLine();
        nMin = Integer.parseInt(sInput.split(" ")[0]);
        nMax = Integer.parseInt(sInput.split(" ")[2]);

        for(int i = nMin; i <= nMax; i++) {
            nMok = i;
            while(nMok > 0) {
                if(nMok % 10 == 8) 
                    nCount++;   
                nMok = (int)(nMok / 10);
            }   // end while
        }   // end for

        System.out.println(nMin + "부터 " + nMax + "까지의 8의 갯수는 : " + nCount + "개 입니다.");
    }

}

2016/12/23 12:06

김성곤

c언어로 해봤습니다. . 정말 멋진 풀이들이 많이있네요 ! 제 짧은 경험으로는 이렇게 장황하게 나오네요 ㅠㅠ

#include<stdio.h>

int sNum[10];

void Count_Divide_Num(int a) {                  //이 함수는 하나의 수를 분해하여 개수를 출력함
    int i, a_1, a_2, a_3, a_4, Num[10];         //a_ 변수들은 각각 1의자리 10의자리 100의자리 1000의 자리를 나타냄
    for (i = 0; i <= 9; i++)Num[i] = 0;
    //printf("%d를 분해하면...\n\n", a);
    if (a < 10) {
        a_1 = a;
    }
    else if (10 <= a&&a < 100) {
        a_2 = a / 10;
        a_1 = a - a_2 * 10;
    }
    else if (100 <= a&&a < 1000) {
        a_3 = a / 100;
        a_2 = (a - a_3 * 100) * 0.1;
        a_1 = a - a_3 * 100 - a_2 * 10;
    }
    else if (1000 <= a&&a < 10000) {
        a_4 = a / 1000;
        a_3 = (a - a_4 * 1000) * 0.01;
        a_2 = (a - a_4 * 1000 - a_3 * 100)*0.1;
        a_1 = a - a_4 * 1000 - a_3 * 100 - a_2 * 10;
    }
    for (i = 0; i <= 9; i++) {
        if (a_1 == i)Num[i] += 1;
        if (a_2 == i)Num[i] += 1;
        if (a_3 == i)Num[i] += 1;
        if (a_4 == i)Num[i] += 1;
        //printf("%d : %d개\n\n", i, Num[i]);            //1부터 10000까지 반복하기 위해 주석처리
        sNum[i] += Num[i];                  
    }                                                   

}

int main() {

    int i;
    for (i = 0; i <= 9; i++)sNum[i] = 0;
    for (i = 0; i <= 10000; i++)
        Count_Divide_Num(i);
    printf("1부터 10000까지 8의 개수는 : %d\n", sNum[7]);
}

2016/12/25 22:49

최 윤준

C(11) gcc v4.9.4

//79COLUMNS////////////////////////////////////////////////////////////////////
// 구글 입사문제 중에서
#include <stdio.h>
#define NUM 8
#define TILL 10000

static int count(int n);

int main(void)
{
    int rst = 0;
    for (int n = 1; n <= TILL; n++)
        rst += count(n);
    printf("%d\n", rst);
    return 0;
}

static int count(int n)
{
    if (! n) return 0;
    return ((n % 10 == NUM)? 1 : 0) + count(n / 10);
}

2016/12/27 11:40

디디

#include <stdio.h>

int main()
{
    int i,j,k,l,m,eight;
    i=j=k=l=m=eight=0;

    for(i=0;i<1;i++)
    {
        for(j=0;j<10;j++)
        {
                for(k=0;k<10;k++)
                {
                        for(l=0;l<10;l++)
                        {
                            for(m=0;m<10;m++)
                            {
if(m==8){eight=eight+1;}if(l==8){eight=eight+1;}if(k==8){eight=eight+1;}if(j==8){eight=eight+1;}  
                                                        }

                        }


                }

        }
    }

    printf("8의 갯수는 %d입니다.\n",eight);

    return 0;
}

C 로 무식하게 풀어봤습니다.

정답은 4000입니다.

2016/12/27 17:55

김 장운

public class Count8 { public static void main(String[] args) { int cnt = 0;

    for (int i =0; i<=10000; i++){
        String temp = String.valueOf(i);
        for(int j =0; j<temp.length(); j++){
            if(temp.charAt(j) == '8'){
                cnt++;
            }
        }
    }

    System.out.println(cnt);

}

}

2016/12/29 11:45

Kim Joosang

코딩 문제라기 보단 수학적 센스를 묻는 게 맞는 것 같네요 그래도 코딩사이트이니 코드도 짰습니다.

#include <iostream>
int main(void)
{
    int sum = 0;
    for(int i = 1; i <= 10000; i++)
    {
        int temp = i;
        while(temp > 0)
        {
            if(temp % 10 == 8)
                sum++;

            temp /= 10;
        }
    }
    std::cout << "Result: " << sum << std::endl;
}

2016/12/29 14:11

김 태범

package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    var cnt int = 0

    for i := 1; i <= 10000; i ++ {
        cnt += strings.Count(strconv.Itoa(i), "8")
    }
    fmt.Println(cnt)
}

2016/12/29 16:46

jkkim

N = 10^K라 가정하고, S(K) = 1부터 10^K 까지의 8의 개수라고 가정하면,

S(0) = 0

S(i) = 10 * S(i-1) + 10^(i-1)

로 정리되므로, 다음과 같이 코드 작성하면 됩니다.

int solution(int N) {
    int S = 0, K = 0, currentN = 1; // initial step, if K = 0
    while (currentN < N) {
        K++;
        currentN *= 10;
        S = 10 * S + (int)Math.pow(10, K-1); // S(K) = 10 * S(K - 1) + 10^(K-1), if K >= 1
    }

    return S;
}

Time Complexity : O(K)

단순히 loop돌면 Time Complexity : O(N * K)

2017/01/02 12:06

뭘로할까


public class cnt8 {

    static int cnt = 0;

    public static int cnt_8(int inputNum){

        if(inputNum%10 == 8) cnt ++;
        if(inputNum > 10) cnt_8(inputNum/10);

        return cnt;
    }

    public static void main(String[] args) {
        for(int i = 1; i<=10000; i++){
            cnt_8(i);
        }
        System.out.println(cnt);

    }
}

2017/01/04 11:07

남 경민

sum = 0

for number in range(1,80):
    str_number = str(number)
    str_len = len(str_number)

    for digit in range(0, str_len):
        if str_number[digit] == '8':
            sum += 1

print sum

2017/01/04 15:23

이름은생략

Scala

var count = 0
(1 to 10000).foreach(i => {
    var f = i
    while (f > 0) {
        if (f % 10 == 8) {
            count = count + 1
        }
        f = f / 10
    }
})
println(count);

2017/01/13 11:40

genius.choi

int result = 0;

            for (int i = 1; i <= 10000; i++)
            {
                int temp = i;

                while (temp != 0)
                {
                    if(temp % 10 == 8)
                    {
                        result++;
                    }

                    temp /= 10;
                }
            }

            Console.WriteLine($"result : {result}");

2017/01/16 16:14

오 예천

숫자 구하는 함수는 fn(숫자)라고 할 때 fn(1234) = fn(123) + fn(4) 라는 점을 이용합니다.

캐시에 매번 계산한 숫자를 저장하고 재사용하여 속도 향상을 노립니다. 캐시 히트율을 높이기 위해서 작은 숫자에서 큰 숫자로 계산을 해야합니다.

import java.util.HashMap;
import java.util.Map;

public class CountNumber {

    public int count(int num, int target) {
        return count(0, num, target);
    }

    private int count(int start, int end, int target) {
        Map<Integer, Integer> cache = new HashMap<>();

        int totalCount = 0;

        for (int i = start; i <= end; i++) {
            Integer cacheCount = cache.get(i / 10);

            int count = (cacheCount == null ? 0 : cacheCount) + (i % 10 == target ? 1 : 0);
            cache.put(i, count);

            totalCount += count;
        }

        return totalCount;
    }

}

2017/01/17 14:27

에이프릴

#include <stdio.h>
int main()
{
    int i = 0;
    int j = 0;
    int cnt = 0;

    for (i = 1; i < 10000; i++)
    {
        j = i;
        while (j)
        {
            if ((j%10!=0)&&(j%10)%8==0)
            {
                cnt = cnt++;        
            }
            j = j / 10;
        }
    }
    printf("%d",cnt);
}

결과 4000

2017/01/20 10:33

장세운

public class Main {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 1; i <= 10000; i++) {
            if (i % 10 == 8)
                count++;
            if (i % 100 / 10 == 8)
                count++;
            if (i % 1000 / 100 == 8)
                count++;
            if (i % 10000 / 1000 == 8)
                count++;

        }
        System.out.println(count);
    }
}

2017/01/21 23:33

심영현

sum [length [x | x <- (show n), x == '8'] | n <- [1..10000]]

2017/01/25 11:45

SJ

흐음

2017/01/30 15:54

임지훈

대단하십니다 다들. 윗분들 풀이보고 따라해봤네요.ㅠㅠ

static int cnt = 0;
    public static void main(String[] args) {
        for(int i=1; i<10001; i++)  calc(i);

        System.out.println(cnt);
    }
    public static int calc(int num){
        if(num%10 == 8) cnt++;
        if(num>10) calc(num/10);
        return cnt;
    }

2017/01/31 16:45

Juni

''' How many '8' from 1 to 10,000? '''

import numpy as np

gen = (x for x in np.linspace(1,10000,10000))

sums = 0 for val in gen: sums += str(val).count('8')

print(sums)

2017/02/01 15:34

남현식

숫자를 모두 문자열로 합친 후 정규표현식을 이용해 개수를 셌습니다

package kr.joao.test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();

        for(int i=1;i<=10000;i++) {
            sb.append(i + "");
        }

        Pattern pattern = Pattern.compile("8");
        Matcher matcher = pattern.matcher(sb.toString());

        int count = 0;
        while (matcher.find()) {
            count++;
        }

        System.out.println(count);

    }
}

2017/02/02 14:08

Juhyeon Kim

[자바스크립트]

var i = 1;
var tmp = '';
var cnt = 0;

for(; i<=10000; i++) {

  tmp = i + '';
  for(var j=0; j<=tmp.length; j++){
    if(tmp[j] == '8') {
      cnt++;
    }
  }

}

console.log(cnt);

총 루프 수 : 48894

2017/02/06 16:25

문 성수

count = 0
for i in range(1, 10001):
    num_list = list(str(i))
    for n in num_list:
        if n == "8":
            count += 1
print(count)

2017/02/09 13:30

유세현


print(sum( sum(1 for x in str(i) if x=='8' ) for i in range(1,10001)))

2017/02/17 12:58

김구경

def count8(n):
    count = 0
    n = str(n)
    for i in n:
        if i == '8':
            count += 1
    return count

x = [count8(i) for i in range(1,10000)]
print(sum(x))

2017/02/17 17:37

wbpark

n=10000
n8=0
for i in range(1,n+1):
    for j in str(i):
        if j=='8':
            n8+=1
print(n8)

숫자를 문자로 바꿔서 쪼개고 더하기 했습니다. 처음 올려봐요~

2017/02/18 17:11

전용준

python 3.5.2

  • answer : 40,000
print(str(list(range(1,10001))).count('8'))

2017/02/21 04:39

강정민

public class Tester {

    public static void main(String[] args) {
        int count = 0;
        for(int i = 1; i <= 10000; i++){
            if(i/1000 == 8)
                count++;
            if((i%1000)/100 == 8)
                count++;
            if((i%100)/10 == 8)
                count++;
            if((i%10) == 8)
                count++;
        }

    }

2017/02/21 17:36

이권동

result = 0
def check(i):
    for t in range(1,10) :
        if i // 10 **t == 0 : return t
        else : continue

for i in range(100) :
    temp = i
    for t in range(0,check(i)) :
        if temp % 10 == 8 :
            result += 1
           # p.append()
        temp = temp // 10

print(result)

2017/02/23 20:29

양도혁

result = 0
for i in range(1,10001) :
    result += str(i).count('8')

print(result)

2017/02/23 20:32

양도혁

str(list(range(1,10001))).count('8')

2017/02/24 17:01

Scott.Jun

str(list(range(1,10001))).count("8")

print(list(range(1,10)))

2017/02/24 19:07

김상엽

str(list(range(1,10001))).count("8")

print(list(range(1,10)))

2017/02/24 19:07

김상엽

public class Test4 {

    public static void main(String[] args) {

        int total = 0;
        for (int i = 1; i <= 10000; i++) {

            int num = i;
            int cnt = 0;
            String value = Integer.toString(num);

            char[] chAr = value.toCharArray();

            for (char ch : chAr) {
                if (Character.getNumericValue(ch) == 8) {
                    cnt+=1;
                }

            }
            total += cnt;
        }

        System.out.println(total);
    }

}

2017/02/28 10:41

Byung Do Kim

print(str(list(range(1,10000+1))).count('8'))

Python 넘나 좋은 것...

2017/02/28 19:24

최해준

python 3.6

li = []
for i in range(1,10001):
    a = ''.join(str(i))
    li.extend(a)

print(li.count(str(8)))

전형적인 입문자 수준 풀이

2017/03/01 20:38

cano

public static void main(String[] args) { int result = 0;

    for(int x = 1; x <= 10000; x++) {
        if(x % 10 == 8) result += 1;
        if((x / 10) % 10 == 8) result += 1;
        if((x / 100) % 10 == 8) result += 1;
        if((x / 1000) % 10 == 8) result += 1;
    }
    System.out.println(result);
}

각 자리수별로 나눠서 카운팅했습니다.

2017/03/04 21:29

정찬영

        static void Main(string[] args)
        {
            try
            {
                int count   = 0;
                char[] chArray = null;

                for(int i = 0; i < 10000; i++)
                {
                    chArray = i.ToString().ToCharArray();

                    foreach (var p in chArray)
                    {
                        if (p.Equals('8'))
                        {
                            count++;
                        }
                    }
                }

                Console.WriteLine(count);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.ReadKey();
            }
        }

2017/03/05 15:39

bobby

/**************************************************************************************************
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?

8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
***************************************************************************************************/

#include<stdio.h>

int Cnt_Eight(int input)
{
    int result = 0;

    if(input/1000==8)
    {
        result++;
        input-=(input/1000)*1000;
    }
    else if(input>1000)
    {
        input-=(input/1000)*1000;
    }

    if(input/100==8)
    {
        result++;
        input-=(input/100)*100;
    }
    else if(input>100)
    {
        input-=(input/100)*100;
    }

    if(input/10==8)
    {
        result++;
        input-=(input/10)*10;
    }
    else if(input>10)
    {
        input-=(input/10)*10;
    }

    if(input/1==8)
    {
        result++;
    }

    return result;
}

int main(void)
{
    int result=0,i;

    for(i=1;i<10000;i++)
    {
        result += Cnt_Eight(i);
    }

    printf("%d",result);

    return 0;
}

전 너무 어렵게 생각했나보네요...

2017/03/05 19:03

이인규

func main(){
    var totalCount = 0
    for i in 1...10000{
        var num = i
        while num != 0 {
            if ( num % 10 == 8 ){
                totalCount += 1
            }
            num = num / 10
        }
    }
    print(totalCount)
}

main()

앞에 멋진 풀이가 많지만... 단순하게 풀이했습니다.

2017/03/06 07:17

YoungHee Jang

public class searchEight{

public static void main(String args[]){

 for(int i=0; i<=10000; i++){
    searchEight(i);
 }
 System.out.println("1 ~ 10000 사이의 8 의 갯수 : " + count);

}

public static int count = 0; public static void searchEight(int num){ if((num % 10) == 8){ count++; } if(num > 10){ searchEight(num/10); } } }

2017/03/06 11:16

정진교

파이썬 3.5.3

count = 0

for x in range(1,10000+1):
    for y in str(x):
        if y == '8':
            count += 1


print(count)

2017/03/06 12:37

JH

int checkSum = 0; int totalSum = 0;

for(int i=1; i<=10000; i++) { checkSum = i.ToString().Split('8').Length - 1; if(checkSum > 0) totalSum += checkSum; }

Console.WriteLine(totalSum);

Print : 4000

2017/03/06 14:25

김도빈

  1. 1~10000 까지의 리스트를 문자열로 변환한다.
  2. 그 문자열에서 '8' 의 갯수를 count 한다
def count8( n ):
    num_list = []
    for i in range( 1, n +1 ):
        num_list.append( i)

    str_list = str( num_list )

    print( str_list.count( str(8) ))


count8( 10000 )

2017/03/12 17:03

Ho Lee

Python 3.6.0 입니다. 이중 for-loop 썼습니다. 답은 4000이라고 나오네요.

freq=0
for num_val in range (1,10000+1):
    for char_val in str(num_val):
        if int(char_val)==8:
            freq+=1
print(freq)


2017/03/16 12:27

c0din9

어.. 원래 아마 코딩으로 풀라고 만든거 같은데 걍 코딩 없이 풀었습니당.

XXX8 인 경우에 1000개의 경우가 있고

XX8X 인 경우에도 1000개의 경우가 있고

X8XX 인 경우에도 1000개의 경우가 있고

8XXX 인 경우에도 1000개의 경우가 있으니깐 4 * 1000 해서 4000입니다.

2017/03/16 22:53

문정민 (◕◡◕)

Java 입니다.

public class Test {

        public static void Excute(){
            int count=0;
            for(int i=1;i<10001;i++){
                count+=counting8(i);
            }
            System.out.println("8갯수 : "+count);
        }

        public static int counting8(int n){
            String strN = String.valueOf(n);
            int c=0;
            for(int i=0;i<strN.length();i++)if(strN.charAt(i)-48 == 8)c++;                      
            return c;
        }

        public static void main(String[] args) {
             Excute();
        }       

}

2017/03/17 14:06

코코팜팜

파이썬 입니다 print(str(list(range(1,10001)).count('8'))

2017/03/18 00:50

Aeroot

java요

2017/03/19 21:28

delphi101

eight = 0
for i in range(1, 10001):
    eight += list(str(i)).count('8')

2017/03/20 11:36

ken choi

int sum = 0;
        for(int i= 0;i<=10000;i++){
            String aa = i+"";
            sum += aa.length() - aa.replaceAll("8","").length();
        }
        System.out.println(sum);

2017/03/22 15:30

Tae Hoon Lee

include

include

using namespace std;

int main() { int num[10] = { 0 }; int ws, j;

for (int i = 1; i < 10001; i++)
{
    for (ws = i;;)
    {
        num[ws % 10]++;
        if (ws < 10) break;
        ws /= 10;
    }
}

cout << num[8];

}

2017/03/25 16:09

PARK JINHOH

연습하고 있어요 :)

min, max = 1, 10000
find_num = 8
count = 0
num = []

for i in range(min, max+1):
    num = str(i)
    for n in range(0, len(num)):
        if int(num[n]) == 8 :
           count += 1
    num = []

print("count : %d" % count)

2017/03/29 09:46

켈리

#include <iostream>

using namespace std;
const int lastIndex = 4;
void main()
{
    int sum = 0;

    int t = 1 / 10;
    int count = 0;

    for (int num = 1; num <= 10000; num++)
    {
        char strNum[6] = { 0, };
        int idx = 0;
        int tempNum = num;
        while (1)
        {
            strNum[idx++] = (tempNum % 10) + '0';
            tempNum = tempNum / 10;

            if (tempNum == 0)
                break;
        }

        for (int i = 0; i < 2; i++)
        {
            strNum[i] ^= strNum[lastIndex - i];
            strNum[lastIndex - i] ^= strNum[i];
            strNum[i] ^= strNum[lastIndex - i];
        }

        for (int i = 0; i < 5; i++)
        {
            if (strNum[i] == '8')
                ++count;
        }
    }


}

2017/04/06 00:38

Ik Jun Choi

package training;

public class Count8 {

    public static void main(String[] args) {
        int iTotalSum = 0;
        for(int i=0;i<10000;i++){
            iTotalSum += count8(i);
        }
        System.out.println("FinalSum => "+iTotalSum);

    }

    public static int count8(int iNum) {
        int iCnt = 0;
        String strNum = String.valueOf(iNum);
        for(int i=0;i<strNum.length();i++){
            if("8".equals(strNum.substring(i, i+1))){
                iCnt++;
            }
        }
        return iCnt;
    }


}

2017/04/08 20:43

acedo

private static int countEight(int n){
        int cnt = 0;

        for(int i=1; i<=n; i++){
            int num = i;
            while(num > 0){
                if(num % 10 == 8){
                    cnt++;
                }
                num = num / 10;
            }
        }

        return cnt;
    }

2017/04/10 21:53

yh

k=[]
for i in range(1,10001):
    for a in str(i):
        k.append(a)
print(k.count('8'))

2017/04/13 17:25

조현

#풀이1
list=[]
for i in range(10):
    for k in range(0,10):
        for a in range(0,10):
            for n in range(0,10):
                list.append(i)
                list.append(k)
                list.append(a)
                list.append(n)

print(list.count(8))

#풀이2
k=[]
for i in range(1,10001):
    for a in str(i):
        k.append(a)
print(k.count('8'))

2017/04/18 13:19

조현

제가 해놓고 다른분들 풀이 보니까 창피하네요..

/*
    1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?

    8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
    (※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
*/
import java.util.*;
class Count_8 {
    public static void main(String[] args) {
        System.out.print("숫자를 입력하세요 : ");
        Scanner robot = new Scanner(System.in);

        int num = robot.nextInt();
        int cnt = 0;

        for(int i = 1 ; i <= num ; i++){
            int cnt_v = i;
            while(true){
                int temp = cnt_v%10;

                if( temp%8 == 0 && temp!=0 ){
                    cnt++;
                }

                cnt_v /= 10;

                if(cnt_v == 0){
                    break;
                }
            }
        }
        System.out.println("8의 개수! : "+cnt);
    }
}

2017/04/19 14:55

SeonKi Lee

public class test2 {

    public static void main(String[] args) {

        int one;
        int ten;
        int hundred;
        int thousand;
        int count=0;

        for(int i=1 ; i<=9999 ; i++)
        {
            if(i>=1 && i<10)
            {
                one = i;
                if(one==8)
                    count++;
            }
            else if(i>=10 && i<100)
            {
                one = i%10;
                ten = i/10;
                if(one==8)
                    count++;
                if(ten==8)
                    count++;
            }
            else if(i>=100 && i<1000)
            {
                one = i%10;
                hundred = i/100;    
                ten = i/10 - hundred*10;
                if(one==8)
                    count++;
                if(ten==8)
                    count++;
                if(hundred==8)
                    count++;
            }
            else if(i>=1000 && i<=9999)
            {
                one = i%10;
                thousand = i/1000;
                hundred = i/100-thousand*10;
                ten = i/10-thousand*100-hundred*10;
                if(one==8)
                    count++;
                if(ten==8)
                    count++;
                if(hundred==8)
                    count++;
                if(thousand==8)
                    count++;
            }   

        }

        System.out.println(count);

    }

}

2017/04/27 13:35

APeach KaKao

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <math.h>
using namespace std;

int fun(int depth);

int mem[4][4];

int main()
{
    memset(&mem[0][0], 0, sizeof(mem));
    cout<<"result:"<<fun(0)<<endl;
    return 0;
}

int fun(int depth)
{
    int i,sum=0;
    if(depth == 3)
        return 1;
    for(i=0;i<10;i++)
    {
        if(mem[i][depth] == 0)
        {
            mem[i][depth] += fun(depth+1);
            if(i==8)
                mem[i][depth] += pow(10, (3-depth)) ;
        }
        sum += mem[i][depth];
    }
    return sum;
}

2017/04/29 12:03

Hanbae Seo

int sum=0;
for(int i=1; i<=10000; i++){
  if((i%10) == 8){sum+=1;}
  if((i%100)/10 == 8){sum+=1;}
  if((i%1000)/100 == 8){sum+=1;}
  if(i/1000 == 8){sum+=1;}
}

print(sum);

답: 4000

2017/05/03 17:01

Han Sanghoon

    public static void main(String[] args) {

        String str = "";
        for(int i = 1; i <= 10000; i++) {

            if (String.valueOf(i).indexOf("8") != -1) {
                str += String.valueOf(i);
            }
        }

        int cnt = 0;
        for(int j = 0; j < str.toString().length(); j++) {
            if ('8' == str.charAt(j)) {
                cnt++;
            }
        }
        System.out.println(cnt);

    }

2017/05/10 00:30

Ethan

public class Algorithm {

public static int resultNum(String str, int n){
    int sum = 0;

    for(int i=0; i<=n; i++){
        if(str.charAt(i) == '8')
            sum++;
    }
    return sum;
}



public static void main(String[] args) {
    // TODO Auto-generated method stub
    int result = 0;
    for(int i=1; i<10000; i++){
        result += resultNum(String.valueOf(i),(int)Math.log10(i));
    }
    System.out.print(result);
}

}

2017/05/10 17:18

dnjs7292

def eight(N):

counter = 0 
for i in range(1,N+1):
    counter += str(i).count('8')
print(counter)

2017/05/14 15:13

김순효

count = 0

for index in range(1, 10001):
    count += len([x for x in str(index) if x == '8'])

무식하게 풀었네요..

2017/05/15 14:31

Taewon Song

#include <iostream>
using namespace std;
int main()
{
    int i, Headnum, Headnum2, Headnum3, count = 0;
    i = 1;
    for(;i < 10000; i++)
    {
        Headnum = (float)i / 10;
        Headnum2 = (float)i / 100;
        Headnum3 = (float)i / 1000;
        if(Headnum3 == 8)
        {
            count += 1;
        }
        if(Headnum2 - Headnum3 * 10 == 8)
        {
            count += 1;
        }
        if(Headnum - Headnum2 * 10 == 8)
        {
            count += 1;
        }
        if(i - Headnum * 10 == 8)
        {
            count += 1;
        }
        printf("%d\n",count);
    }
}

한줄... 허탈하네요...

2017/05/20 19:29

S ReolSt

string strNum;
int cnt = 0;

for (int i = 1; i <= 10000; i++)
{
    strNum = i.ToString();

    foreach (char a in strNum)
    {
        if (a == '8') cnt++;
    }
}

2017/05/23 04:56

양은경

python 3.6 일단 한줄 풀이

>>> sum([str(i).count('8') for i in range(1,10000)])
4000

2017/05/24 01:12

예강효빠

JAVA

        int cnt = 0;
        for(int i = 1; i<=10000 ; i++){
            String e = Integer.toString(i);
            char[] cAr = e.toCharArray();

            for(int wow = 0; wow<cAr.length ; wow++ ){
                if(cAr[wow] == '8'){
                    cnt++;
                }
            }
        }
        System.out.println(cnt);

2017/05/24 04:48

Kim.Choc

sum=0
for i in range(1,10001):
      sum+=str(i).count("8")
print(sum)

한줄코드 보고 감탄했습니다

2017/05/27 23:42

김민기

x = 1
y = []
n = 0
while n < 10000 :
    if x < 10 :
        x = str(x)
        y.append(x[0])
    elif 10 <= x < 100 :
        x = str(x)
        y.append(x[0])
        y.append(x[1])
    elif 100 <= x < 1000 :
        x = str(x)
        y.append(x[0])
        y.append(x[1])
        y.append(x[2])
    elif 1000 <= x < 10000 :
        x = str(x)
        y.append(x[0])
        y.append(x[1])
        y.append(x[2])
        y.append(x[3])
    else :
        x = str(x)
        y.append(x[0])
        y.append(x[1])
        y.append(x[2])
        y.append(x[3])
        y.append(x[4])
    x = int(x)
    n = n + 1
    x = x + 1

k = 1
l = 0
while k <= 10000 :
    l = k + l
    k  = k + 1

m = 0
g = 0

while m < l :
    if y[m] == 8 :
        g = g + 1


print("1부터 10000까지 8이라는 숫자는 총 %d번 나온다" % g)


이러면 나올거 같긴 한데 실행시킨지 10분이 넘도록 제 컴퓨터가 연산해내지 못하는걸 보면 어마어마한 똥 프로그램인 듯 합니다!


적어놓고 다른 분들이 올리신거 보니까 반성하게 되네요... ㅠㅠ 뭐야 한줄은 엥엥

2017/05/29 00:04

TohnoSiki

function countEight(n) {
    count = 0;
    for(var i = 1; i <= n; i++) {
        var str8 = i.toString();
        var matched8 = str8.match(/8/g);
        matched8 ? count += matched8.length : null;
    }
    return count;
}

2017/05/29 18:38

hyunwoo kim

cnt = 0
for n in range(10001):
    string=str(n)
    for i in range(len(string)):
        if string[i]=='8':
            cnt+=1

print(cnt)

2017/05/29 21:10

나후승

JAVA count=4000

    int count=0;

    for(int i=1; i<10000; i++){
        String leng=Integer.toString(i);
        for(int j=0; j<leng.length(); j++){
            int ex = Integer.parseInt(Character.toString(leng.charAt(j)));
            if(ex==8){
            count++;
            }
        }
    }
    System.out.println("count : "+count);

2017/05/30 15:35

강혜지

c로 풀이

#include <stdio.h>
int main(void)
{
    int i,j,num=0;

    for(i=1;i<=10000;i++) for(j=1;j<=1000;j*=10) if(((i/j)%10)==8) num++;
    printf("%d\n",num);
}

2017/05/31 09:55

박동준

엑셀 vba풀이

Dim sum as long

For i=1 to 10000

For s=1 to len(i)

If mid(i,s,1)=8 then:sum=sum+1

Next

Next

Msgbox sum & "번"

2017/06/09 23:08

조민수

javascript(ES6)

// 1
var count = Array.from({length: 10000}, (v, k) => k + 1)
                 .join()
                 .split('')
                 .filter(n => n === "8")
                 .length; 
console.log(count);

// 2
var count = Array.from({length: 10000}, (v, k) => k + 1)
                 .join()
                 .split("8")
                 .length - 1; 
console.log(count);

2017/06/14 10:27

funnystyle

let count = 0;
let num = 0;

let palFunc = () => {
    for(let i = 1; i <= 1000; i++){
        for(let j = 0; j < (i+'').length; j++){
            num = ((i+'').charAt(j))*1;
            if(num%8==0 && num != 0){
                console.log(num);
                count++;
            }
        }
    }
    return count;
}

console.log(palFunc());

2017/06/14 22:04

redshark

def countnum(x):
    count = str(x).count('8')
    return(count)


total = 0
for i in range(0,10000):
    total = total + countnum(i)

print (total)

2017/06/15 10:20

Bo Hyun Seo

    public static void main(String[] args) {
        int cnt=0;
        for(int i=1;i<=9999;i++){
            if(i%10==8)cnt++;
            if((i/10)%10==8)cnt++;
            if((i/100)%10==8)cnt++;
            if((i/1000)%10==8)cnt++;
        }
        System.out.println(cnt);
    }

2017/06/15 21:24

kihyun lee

#include<stdio.h>

int main(void)
{
    int i;
    int count=0;

    for (i = 0;i <= 10000;i++) {
        if (i / 10 == 0) {
            if (i % 10 == 8)
                count++;
        }
        else if (i / 100 == 0) {
            if (i % 10 == 8)
                count++;
            if ((i / 10) % 10 == 8)
                count++;
        }
        else if (i / 1000 == 0) {
            if (i % 10 == 8)
                count++;
            if ((i / 10) % 10 == 8)
                count++;
            if (((i / 10) / 10) % 10 == 8)
                count++;
        }
        else {
            if (i % 10 == 8)
                count++;
            if ((i / 10) % 10 == 8)
                count++;
            if (((i / 10) / 10) % 10 == 8)
                count++;
            if ((((i / 10) / 10) / 10) % 10 == 8)
                count++;
        }

    }

    printf("%d", count);
}

2017/06/18 14:56

조밍

파이썬 한 줄 코드 보고.. 조용히 제 코드 지웠네요 ㅡ,.ㅡ

2017/06/19 14:34

정범구

파이썬으로 작성 하였습니다.

count = 0

for i in range(1,10001):

for j in str(i):

    if int(j) == 8:

        count +=1

print(count)

2017/06/27 22:10

semipooh

value=0
for member in range(10001):
    num = list(str(member))
    num_eight = num.count('8')
    value = value + num_eight

print(value)

2017/06/28 20:27

안성준

public class numbersOfEight
{
  public static void main(String[] args)
  {
    int result = 0;
    for(int i = 0; i <= 10000; i++)
    {
      int temp = i;
      while(temp > 0)
      {
        if(temp % 10 == 8)
          result ++;

        temp = temp / 10;
      }
    }

    System.out.println(result);
  }
}

2017/07/01 15:03

신종혁

간단한 정규식을 이용해서 풀어봤습니다.

import re
total = 0

p = re.compile('8')

for i in range(10000):
    t = str(i)

    if '8' in t:
        total += len(p.findall(t))


print total

2017/07/04 10:15

강동인

public class Ex003 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int sumOfEight=0;
        for(int i=1; i<=10000; i++) {
            int temp = i;
            do {
                if(temp%10 == 8)
                    sumOfEight++;
                temp /= 10;
            }while(temp != 0);
        }
        System.out.println("8숫자의 총합: " + sumOfEight);

    }
}

2017/07/04 12:43

pg

앞에 좋은 풀이가 많았지만 그래도 연습차원에서 Python으로 풀어봤습니다.

print(len([d for x in range(1, 10001) for d in str(x) if d is '8']))

적고 보니, 아래가 더 간단하게 보이네요.

print(sum(str(x).count('8') for x in range(1, 10001)))

2017/07/04 21:07

SOUP

def count8(ub):
    cnt = 0
    for i in range(1, ub+1):
        cnt += str(i).count('8')
    return cnt

# ub = 10^x, x>=2 라고 가정
# count8_rec(1000) = 8xx 100개 + count8_rec(100) * 10개
def count8_rec(ub):  
    if ub is 10: return 1
    return  ub // 10 + 10 * count8_rec(ub // 10)

print(count8(10000), count8_rec(10000))

두가지 다 해 봤습니다. 오.. 다른 풀이를 보니 위에 건 한 줄로 되는군요. 아직 익숙하질 않음

2017/07/05 06:22

Noname

sum = 0 for I in range(1, 10001): num = 0 a_str = str(i) a_list = list(a_atr) for count in range(0, Len(a_str)): if a_list[count] == '8': num = num + 1 sum = sum + num print(num)

2017/07/05 17:30

minhyeok lee

[Python 3.6]

print(''.join(str(i) for i in range(10001)).count('8'))

2017/07/11 13:54

Eliya

def count8(num):
    count = 0
    for i in str(num):
        if i == '8':
            count += 1
    return count

answer = 0

for j in range(1,10001):
    answer += count8(j)

print(answer)

2017/07/14 21:11

ynwag94

package java_tutorial;

public class Count8 {

    public static void main(String[] args) {

        int count = 0;

        for(int i = 1; i < 10000; i++)
        {
            if(i/1000==8) {count++;}
            if((i/100)%10==8) {count++;}
            if((i/10)%10==8) {count++;}
            if(i%10==8) {count++;}      
        }

        System.out.println("The Answer is " + count++);
    }

}

2017/07/15 15:19

최원석

#include <stdio.h>
#include <string.h>
#define _CRT_SECURE_NO_WARNNINGS
#define MAX 39000

int total();

int main()
{
    int res;
    res = total();
    printf("Total : %d\n", res);
    return 0;
}

int total()
{
    char string[MAX] = { 0 };
    char tmp[6];
    int i, res=0;

    for (i = 1; i <= 10000; i++) {
        sprintf(tmp, "%d", i);
        strcat(string, tmp);
    }

    for (i = 0; i < strlen(string); i++)
        if (string[i] == '8')
            res++;

    return res;
}

2017/07/20 13:44

정동건

#include<stdio.h>

int main(void)
{
    int i;
    int cnt = 0;
    for (i = 1; i <= 10000; i++)
    {
        if (i % 10 == 8)
            cnt += 1;
        if ((i / 10)%10 == 8)
            cnt += 1;
        if ((i / 100)%10 == 8)
            cnt += 1;
        if (i / 1000 == 8)
            cnt += 1;
    }
    printf("%d\n", cnt);
    return 0;
}

2017/07/21 14:52

MAKESOME

#include <stdio.h>
#define START 1
#define END 10000

int result;

void FindEightToAdd(int); //8의 개수 더하기

int main()
{
    int i;

    //8의 개수 총합
    for (i = START; i <= END; i++)
    {
        FindEightToAdd(i);
    }

    printf("%d\n", result);

    return 0;
}

void FindEightToAdd(int input)
{
    if (input % 10 == 8)
    {
        result++;
    }

    if (input > 0)
    {
        FindEightToAdd(input / 10);
    }
}

2017/07/23 18:35

스봉

print(','.join( [ str(a) for a in range(10001)] ).count('8'))

2017/07/24 02:30

이재희

print(str(list(range(1, 10001))).count('8'))

2017/07/26 22:28

다크엔젤

public class Count8 {
    public static void main(String[] args) {
        int cnt=0;
        for(int i=0; i<10000; i++)
            cnt += eightCount(i,0);
        System.out.println(cnt);
    }

    public static int eightCount(int n, int cnt) {
        if(n%10 == 8) cnt++;
        if(n/10 > 0) return eightCount(n/10,cnt);
        return cnt;
    }
}

2017/07/31 15:26

곽철이

import java.util.Arrays;
import java.util.stream.IntStream;

public class Lv2 {
    public void func(int num) {
        int count = 0;
        char[] arr = Arrays.toString(IntStream.range(1, num+1).toArray()).toCharArray(); 
        for (char c : arr) if (c == '8') count++;
        System.out.println(count);
    }

    public static void main(String[] args) {
        Lv2 obj = new Lv2();
        obj.func(10000);
    }
}

2017/08/01 19:28

sunga

l = range(1, 10001)
l2 = [str(x) for x in l]

print sum([x.count('8') for x in l2])

2017/08/02 20:14

Alberto Yeo

JAVA

int cnt = 0;

for (int i = 1; i <= 10000; i++) {
    char[] c = Integer.toString(i).toCharArray();
    int len = c.length;

    for (int j = 0; j < len; j++) {
        if (c[j] == '8') {
            cnt++;
        }
    }
}

System.out.println(cnt);

2017/08/03 10:46

androot

sum = 0
for n in range(1,10001):
    b = [int(i) for i in str(n)]
    for num in b:
        if num ==8:
           sum += 1
print(sum)

2017/08/03 11:38

이현우

public class Calculate {

    public static void main(String[] args) {

        int maxNum = 10000;
        int cnt = 0;
        String tmp = "";

        for (int i=1 ; i<=maxNum ; i++) {
            tmp = i+"";
            cnt += tmp.length()-tmp.replaceAll("8", "").length();
        }
        System.out.println("cnt : "+cnt);
    }
}

2017/08/04 16:56

SH

    public static void getNumberCnt() {

        int splitLength = 0;
        for(int i=1; i<=10000; i++) {
            splitLength += String.valueOf(i).split("8",-1).length -1;
        }
        System.out.println(splitLength);
    }

    public static void main(String[] args) {
        getNumberCnt();
    }

답은 4000

2017/08/05 17:38

jaehun song

sum = 0
for i in range(1, 10001):
    sum += str(i).count('8')
print(sum)

4000
숫자를 문자열로 바꾼뒤 개수를 세서 합했습니다.

2017/08/06 19:39

핏스

count=0 for i in range(10000): while i>0: if i%10==8 count++ i= i//10

print(count)

2017/08/11 05:02

김초영

import string

eight_count=0
for i in range(1,10001):
    i=str(i)
    temp_count=i.count('8')
    eight_count+=temp_count
print(eight_count)

2017/08/13 22:18

Jung Daehyun

count=0
for i in range(1,10000+1):
    count+=str(i).count("8")

print(count)

2017/08/21 00:05

iamm00n

풀고 나서 보니 이미 있네요.. 죄송합니다. (푼거 안보이게 할수 없나요 나만 보게 ㅜㅜ)

print(''.join(list([str(x) for x in range(1,10001)])).count('8'))

2017/08/21 17:33

piko

```{.python}

```list(range(1,10001))

2017/08/22 00:46

서기훈

```{.python}

```print str(range(1,10001)).count('8')

2017/08/22 00:47

서기훈

public class Main {
    public static void main(String[] args) {
        int cnt = 0;
        for (int i=1; i<=10000; i++) {
            if (i/1000%10 == 8) cnt++;
            if (i/100%10 == 8) cnt++;
            if (i/10%10 == 8) cnt++;
            if (i%10 == 8) cnt++;
        }
        System.out.println(cnt + "번");
    }
}

2017/08/23 16:59

임주성

result = 0
for i in range(1,10001):
    trans_str = str(i)
    for j in trans_str:
        if(int(j) == 8): result+=1
print(result)

2017/08/25 15:14

Sangwoon Park


public class Example7 {

    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 10000; i++) {
            sum += GetCounter(String.valueOf(i));
        }

        System.out.println(sum);

    }

    private static int GetCounter(String s) {
        int counter = 0;
        for (Character c : s.toCharArray()) {
            if (c.equals('8')) {
                counter++;
            }
        }
        return counter;
    }
}

뭔가 람다로 간단하게 할 수 있는 방법이 있을것 같은데... 모르겠네요

2017/08/28 18:04

흑돼지

// CD007 - 구글 입사문제 중에서
package main

import (
    "fmt"
    "strings"
)

func main() {
    count := 0
    for i := 1; i <= 10000; i++ {
        count += count8(fmt.Sprint(i))
    }
    fmt.Println(count)
}

// count "8"s in aString
func count8(aString string) int {
    count := strings.Count(aString, "8")
    return count
}

2017/08/29 09:15

mohenjo

b = []
for i in range(1, 10001):
    a = str(i)
    b += a
    c = b.count('8')
print(c)

2017/08/31 15:38

검은콩

result=0
for i in range(1,10001):
    result+=str(i).count('8')
print(result)


2017/08/31 20:06

impri

# python 3.6
print(sum([str(i).count("8") for i in range(1, 10001)]))
# ans: 4000

2017/09/02 18:12

mohenjo

public class Ex3 {
    public static int cnt;

    public static void main(String[] args) {
        for(int i=1;i<10000;i++) {
            count(i);
        }

        System.out.println(cnt);

    }

    public static void count(int number) {
        int[] no = new int[4];

        no[0] = number/1000;
        no[1] = (number%1000)/100;
        no[2] = (number%100)/10;
        no[3] = (number%10);

        for(int i=0;i<no.length;i++) {
            if(no[i] == 8) {
                cnt++;
            }
        }

    }
}

2017/09/05 16:29

염현우

문제를 좀더 응용해서 사용자가 입력한 숫자에서 8을 카운팅 하는것으로 풀었습니다.

package org.Solve_3_keyboard_scan;

import java.util.Scanner;

import java.util.ArrayList;

public class Solve_3_keyborad_scan { public static void main(String[] args){

    Number test1 = new Number();
    test1.main();
    test1.Collection_8();
    test1.Count_8();

    System.out.println(test1.result);

// for (int p =0 ; p<test1.collection_number.size();p++){ // System.out.println(test1.collection_number.get(p)); // } }

} class Number { ArrayList number = new ArrayList(); ArrayList collection_number = new ArrayList(); int limit; int result;

public void main() {
    System.out.println("자연수를 입력해주세요 : ");
    Scanner sc = new Scanner(System.in);
    limit = sc.nextInt();

    for (int t = 0; t < limit + 1; t++) {
        number.add(t);
    }
}

public void Collection_8() {

    for (int origin_N = 1; origin_N < number.size(); origin_N++) {
        String length1 = String.valueOf((int) number.get(origin_N));
        int length2 = length1.length();
        if (length2 == 1) {
            String collection_1 = length1.substring(0);
            collection_number.add(collection_1);
        } else {
            for (int where = 0; where < length2; where++) {
                String collection_2 = length1.substring(where, where + 1);
                collection_number.add(collection_2);
            }
        }
    }
}

public void Count_8() {
    for (int Count = 0; Count < collection_number.size(); Count++) {
        if (Integer.parseInt((String)collection_number.get(Count))== 8) {
            result = result + 1;
        } else {

        }

    }
}

}

2017/09/06 17:42

손현기

파이썬입니다.



print(sum([str(n).count('8') for n in range(1, 10000)]))

2017/09/15 13:18

김동환

파이썬 3.6버전입니다.

num_list에 1~10000까지 각 숫자에 들어간 8의 개수를 list로 넣어서 sum함수로 더했습니다.

num_list=[]
for num in range(1,10001):
    num_str=str(num)
    num_list.append(num_str.count('8'))

print(sum(num_list))

2017/09/17 22:27

루룰루랄라

#include <iostream>
#include <vector>
#include <stack>
#include <math.h>

using namespace std;


int check_digit(int num) {
    int count = 0;
    while (1) {
        count++;
        if (num < pow(10, count))
            return count;
    }
}

int pick_num(int num, int digit) {
    int num1 = pow(10, digit);
    int num2 = pow(10, digit - 1);
    int result = (num%num1 - num%num2)/pow(10,digit-1);
    return result;
}

int count_8(int num) {
    int digit = check_digit(num);
    int count = 0;
    for (int i = 1; i <= digit; i++) {
        if (pick_num(num, i) == 8)
            count++;
    }
    return count;
}



int main() {
    int num = 10;
    cout << "Type number" << endl;
    cin >> num;
    int sum = 0;
    for (int i = 0; i <= num; i++) {
        sum += count_8(i) * 8;
    }
    cout << sum << endl;

}

2017/09/19 10:47

김기훈

class count():

def counts(self): counteight = 0 for num in range(1,100): num = list(str(num)) for number in num: if number == '8': counteight = counteight + 1

return counteight

a = count() b = a.counts() print(b)

2017/09/20 10:20

rlaxorwn12

package codingdojang;

public class ex7 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int count = 0;
    for(int i=0; i < 10001; i++) {
        if((i/1000)%10 == 8) count++;
        if((i/100)%10 == 8) count++;
        if((i/10)%10 == 8) count++;
        if((i/1)%10 == 8) count++;
    }
    System.out.println(count);
}

}

2017/09/26 18:28

이병호

def count_8(number):
    s = str(number)
    count = 0
    for n in range(len(s)):
        if 8 == int(s[n]): count += 1

    return count

total = 0
for n in range(10000):
    total += count_8(n)

2017/09/28 19:00

thanatoz

단순 사칙 연산으로 풀었습니다만, 계산 과정에서 각 자릿수로 나눈 나머지에서 다시 나눠서 구했습니다. 먼저 각 자릿수로 나누고나서 나머지로 구하는 식도 있던데 서로 정답을 구할 순 있었습니다. 어떤게 더 나은지는 잘 모르겠네요..

public class googleMatter {

    public static void main(String[] args) {
        int count = 0;

        for(int number = 1; number < 10000; number ++) {
            if( number / 1000 == 8 ) {
                count ++;
            } 
            if( (number % 1000) / 100 == 8 ) {
                count ++;
            }
            if( (number % 100) / 10 == 8 ) {
                count ++;
            }
            if( number % 10 == 8 ) {
                count ++;
            }
        }
        System.out.println("Result : " +count);
    }
}

2017/10/01 09:29

SungWook Jung

function solve() {
    let count = 0;
    for(let i = 8; i <= 10000; i+=10){
        let n = i;
        do {
            if(n%10 === 8){
                count++;
            }
            n = Math.floor(n/10);
        } while(n > 1);
    }
    return count;
}

console.log(solve());

2017/10/01 15:48

이준열

package 구글문제;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

/*
 * 1~10000까지의 서 8이라는 숫자는 몇게 나오냐
 */
public class GoogleProblem {
    public static void main(String[] args)throws IOException {
        int HowEight=0; 
        String getStr;

        System.out.println("숫자를 입력주세요 : ");
        int input = new Scanner(System.in).nextInt();

        FileOutputStream fos = new FileOutputStream("Log.txt");
        for(int i=1; i<input; i++) {
            getStr = i+"";
            if(getStr.contains("8")) {
                String sub [] = new String[getStr.length()];
                for(int j=0; j<sub.length; j++) {
                    sub[j] = getStr.substring(j, j+1);
                }//for
                String buf = Arrays.toString(sub)+"\n";
                fos.write(buf.getBytes());
                System.out.println(Arrays.toString(sub));
                for(int k=0; k<sub.length; k++) {
                    if(sub[k].equals("8"))
                        ++HowEight;
                    else 
                        continue;
                }
            }
        }

        System.out.println("total : "+HowEight);

        }
    }

2017/10/02 00:00

최민준

def counting(n, m):
    nist = []
    nist = list(str(n))
    count = 0
    for i in nist:
        if i == str(m):
            count = count + 1
    return count


count = 0
for i in range(1, 10001):
    count = count + counting(i, 8)


print (count)

2017/10/08 03:21

Yungbin Kim

#include <stdio.h>
int main()
{
    int m = 0;
    int o = 0;
    int s = 0;
    for(int i = 0; i < 10000; i++)
    {
        o = i;
        while(o > 0) 
        {
            m = o % 10;
            o = o / 10;
            if(m == 8)
            {
                s++;
            }
        }
    }
    printf("%d\n", s);
}

2017/10/13 22:17

이 종성

간단한 해법도 존재하군요

    int count = 0;
    for (int i = 0; i <= 10000; i++)
    {
        int temp = i;
        while (temp)
        {
            if (temp % 10 == 8) count++;
            temp /= 10;
        }
    }
    cout << "총 갯수 : " << count << endl;

2017/10/15 18:14

lim


alist = []
for i in range(1,10001):
    for j in list(str(i)):
        if '8' in j:
            alist.append(j)
alist.count('8')

저는 숫자를 각 자리로 쪼개서 리스트로 만들고, 그 안에 8이 있으면 모두 alist에 삽입하는 형식으로 alist를 만들었습니다. 그리고 그 리스트에서 8을 세었습니다. 언어는 파이썬입니다.

2017/10/17 20:05

정재훈

number = 0
for x in range(1,10001):
    number += str(x).count('8')

2017/10/20 11:31

김동근

print("".join([str(x) for x in range(1, 10001) if "8" in str(x)]).count("8"))

한줄 코딩 재밌네요

2017/10/21 17:52

캘린더

public class CountEight {
    public static void main(String[] args) {
        int cnt = 0;

        for(int i = 1; i <= 10000; i++){
            if(i%10 == 8) cnt++;
            if((i/10)%10 == 8) cnt++;
            if((i/100)%10 == 8) cnt++;
            if((i/1000)%10 == 8) cnt++;
        }       
        System.out.println(cnt);
    }
}

2017/10/27 17:23

Yongjun Kim

# 한글 처리 in Atom 1.21.1 + Anaconda(Python 3.6.3) on Mac
import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')

# 1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
# 8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
# (※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)

print(''.join(str(i) for i in range(1, 10001)).count('8'))

2017/11/04 22:48

Jace Alan

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace numberCounting
{
    class Program
    {
        static void Main(string[] args)
        {
            const int NUM = 8;
            int divideNum = 1;
            int count = 0;

            //각 자릿수에서 8이면 count를 올림
            for(int i = 1; i <= 10000; i++)
            {
                while(i / divideNum >= 1)
                {
                    int temp;
                    temp = (i % (divideNum * 10)) / divideNum;

                    //Console.WriteLine(i + " " + temp);
                    if (temp == 8)
                    {
                        count++;
                    }
                    divideNum *= 10;
                }
                divideNum = 1;
            }
            Console.WriteLine(count);
        }
    }
}

2017/11/05 22:32

와디더

public static int countStr(String str){ String[] arr = str.split("8"); int result = arr.length -1; return result; }

2017/11/07 11:36

kim

JAVA

public class Main {

    static int chk(int n) {
        int ret = 0;
        while (n != 0) {
            if (n % 10 == 8) {
                ret++;
            }
            n /= 10;
        }
        return ret;
    }

    public static void main(String[] args) {
        int rst = 0;
        for (int i = 1; i <= 10000; i++) {
            rst += chk(i);
        }
        System.out.println(rst);
    }
}

2017/11/15 10:28

디디

    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            for(int i = 1; i <= 10000; i++)
            {
                string number = i.ToString();
                for(int j = 0; j < number.Length; j++)
                {
                    if(number[j] == '8')
                    {
                        count++;
                    }
                }

            }
            Console.WriteLine(count);
        }
    }

2017/11/17 20:43

김종철

def getEightDigitCount(num):
    numStr = str(num)
    result = 0;
    for digit in numStr:
        if digit == "8":
            result = result + 1
    return result

MAX_NUM = 1000
for i in range(1, MAX_NUM):
    print(str(i) + "," + str(getEightDigitCount(i)))

newList = [getEightDigitCount(i) for i in range(1, MAX_NUM)]
print(sum(newList))

2017/11/20 11:22

Cley Park

#define MAX 10000

int main()
{
    int i;
    int a;
    int k;
    int c=0;

    for (i = 1; i <= MAX; i++)
    {
        a = i;
        while (a > 0)
        {
            k = a % 10;
            if (k == 8)
                c++;

            a /= 10;
        }
    }
    printf("%d", c);


}

2017/11/20 15:18

junpil lee

Common Lisp

(loop for n from 1 to 10000 sum ((lambda (num) (count #\8 (prin1-to-string num))) n))
4000

2017/11/24 10:07

리스프

const countEight = num => {
  return Array.from(new Array(num), (_, i) => i + 1).join().match(/8/g).length;
};

console.log(countEight(10000));

2017/11/24 18:01

huna

cnt = 0
for num in range(10000):
    while num != 0:
        if num%10==8:
            cnt += 1

        if num>10: num = num/10
        else: break

print cnt

문자열로 처리하는 게 10씩 나눠서 처리하는 것보다 빠르다니 ..

2017/11/28 13:22

탐나

public class Google { private static int count = 0; public static void main(String args[]){ for(int num = 1 ; num <= 10000; num++){ String numStr = String.valueOf(num); int sl = numStr.length(); for (int i=0; i < sl; i++){ if ( numStr.charAt(i) == '8') count++; } } System.out.println("count is "+count); } }

2017/12/04 15:03

떼디

count = 0
for i in range(1,10000):
    goo = str(i)
    for a in range(len(goo)):
        if(goo[a] == '8'):
            count+=1 
print(count)

2017/12/08 18:45

redshark

NumCnt = 0;
for x in range(10000):
    for idx in range(0, len(str(x))):
        if (str(x))[idx] == "8":
            NumCnt = NumCnt + 1

print(str(NumCnt))

2017/12/11 15:20

이형영

#1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
#8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
#(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)

# count = 0
# the_eight = "8"
# for eight in range(1,10000):
#     if the_eight in str(eight):
#         length_eight = len(str(eight))
#         for x in range(length_eight):
#             if str(eight)[x] == the_eight:
#                 count += 1
#                 print (eight, count)
#             else:
#                 pass
#     else:
#         pass
#
# print (count)

#참고하여 쓴 답 
print ((str(list(range(1,10000)))).count('8'))

2017/12/11 22:16

이경수

def eight(x):
    return x == "8"

num8=0
for i in range(1,10001):
   number = str(i)
   a = list(number)
   num8=num8+len(filter(eight,a))
print num8

2017/12/12 02:28

영이

print(sum([str(i).count('8') for i in range(7, 9999)]))

2017/12/13 15:16

빗나감

import re

int_n = list(range(1,10001))
int_str = str(int_n)
k = re.findall("8", int_str)
print(len(k))

2017/12/15 09:30

홍철현

package programming;

public class oiler {

    public static void main(String[] args) {

          int count = 0;
            for (int i = 1; i <= 10000; i++) {

                if ((i % 10) == 8)
                    count++;
                if (((i / 10) % 10) == 8)
                    count++;
                if (((i / 100) % 10) == 8)
                    count++;
                if ((i / 1000) == 8)
                    count++;

            }
            System.out.println(count);
    }

}

2017/12/18 06:08

쫑티

count = 0

for i in range(1,10001): s = str(i) count += s.count("8")

print(count)

2017/12/19 12:33

ekfrqkf

count = 0
for i in range(1,10001):
    for x in str(i):
        if x == "8":
            count += 1
print(count)

#고수분들 한줄 코딩 리스펙트합니다! 저는 아직 초보라 이렇게 풀어써야하는데말이죠 ㅎㅎ

2017/12/22 13:49

june davis

y = list(y for y in str(list(range(1,10001))) if '8' in y)
print(len(y))

2017/12/24 16:27

얏홍

public class howManyTimes8 {

    // 숫자 n에 대하여 8이 몇개 들어있는지 알 수 있음
    public static int catch8(int input) {
        String num = ""+input+"";
        int size = num.length();
        char[] arr = new char[size];
        for(int i=0; i<size; i++) {
            arr[i] = num.charAt(i);
        }
        // ㄴㅡㅡ input값의 각 자리수가 들어간 배열 arr 생성


        int count=0;
        for(int i=0; i<size; i++) {
            if(arr[i] == '8')
                count++;
        }
        return count;
    }

    // 1부터 n까지 catch8() 실행
    public static int count8(int n) {
        int result=0;
        for(int i=1; i<=n; i++) {
            result = result + catch8(i);
        }
        System.out.println(result);
        return result;
    }

    public static void main(String[] args) {
        count8(100);

    }
}

2017/12/25 13:53

김기덕

s = []

for i in range(10000):
    s += str(i+1)

print(s.count('8'))

2017/12/28 21:53

이준우

파이썬 3.6

count = 0

for i in range(1,10001):
    if '8' in str(i):
        count += str(i).count('8')

print(count)
  • 결과값
4000

2018/01/01 11:25

justbegin

파이썬 입니다.

cnt=0
for i in range(1,10001):
    for j in range(len(str(i))):
        if str(i)[j]=='8':
            cnt=cnt+1
print(cnt)

2018/01/02 17:29

Ilhoon Kang

print(sum(str(i).count('8') for i in range(1, 10001)))

2018/01/04 00:04

김호현

    final static int MAX = 10000;
    static int cnt = 0;

    public static void main(String[] args) {
        main m = new main();
        for(int i = 0; i < MAX; i++)
        {
            m.counting_eight(i+1);
        }
        System.out.println(cnt);
    }

    public void counting_eight(int num) {
        if (num % 10 == 8)
            cnt++;
        if (num > 10)
            counting_eight(num / 10);
    }

자바요... 허허허....

2018/01/05 10:08

강승규

public class Example { public static void main(String[] args) { int sum=0; for(int i=1; i<=10000; ++i) { String temp = String.valueOf(i); for(int j=0; j<temp.length(); ++j) if(temp.charAt(j) == '8') ++sum; }

    System.out.println(sum);

}

}

public class Example 
{
    public static void main(String[] args) 
    {
        int sum=0;
        for(int i=1; i<=10000; ++i)
        {
            String temp = String.valueOf(i);
            for(int j=0; j<temp.length(); ++j)
                if(temp.charAt(j) == '8')
                    ++sum;
        }

        System.out.println(sum);

    }
}

2018/01/09 17:55

최태훈

print(sum(str(x).count('8') for x in range(1, 10001)))


2018/01/09 23:11

임정원

파이썬

import re

print(sum([re.findall('[8]', str(i)).count('8') for i in range(10000)]))

2018/01/11 14:34

이택성

자바

        int count = 0;
        for(int i = 0; i < 10000; i++) {
            String ans = String.valueOf(i);
            for(int j = 0; j < ans.length(); j++) {
                if(ans.charAt(j) == '8') count += 1;
            }
        }
        System.out.println(count);

2018/01/11 23:56

이택성

public static void main(String[] args) {

    int count = 0; // 8의 개수.

    for(int i = 1; i <= 10000; i++)
    {
        int n = i; // i 값을 n에 대입.

        while(n > 0)
        {
            if(n % 10 == 8) // 각 자리 숫자를 10으로 나눠서 8이 나오면 count++.
            count++;
            n = n / 10; // n을 한자리 줄여줌.
        }
    }
    System.out.println(count);
}

답이 4000이 나왔는데 맞나요??

2018/01/12 15:39

Byam_Gyu

tot=0
for i in range(10001):
    i = str(i)
    a = list(i)
    for j in range(len(a)):
        if int(a[j])==8:
            tot += 1
print(tot)

2018/01/14 16:47

추천꾸욱~!

google<-function(x,y,n){
  count <- 0
  for(i in x:y){
  tmp <- unlist(strsplit(as.character(i),split=character(0)))
    for(j in 1:NROW(tmp)){
      if(tmp[j]==n){ count <- count+1 }
    }
  }
  print(count)
}

2018/01/18 14:59

Dong-il kim

r로 풀었습니다.

a<-0
for(i in 1:10000){
  if(i%%10==8){
    a<-a+1}
  if((i%/%10)%%10==8){
    a<-a+1}
  if((i%/%100)%%10==8){
    a<-a+1}
  if((i%/%1000)%%10==8){
    a<-a+1}
}
print(a)
``````{.r}

2018/01/18 16:04

Seunghyuck Kim

r = 0
for i in range(1, 10001):
    r += str(i).count('8')
print(r)

2018/01/20 10:55

whmj

count = 0

for i in range(10000):
    if i//1000 == 8:
        count += 1
    if i//100%10 == 8:
        count += 1
    if i//10%10 == 8:
        count += 1
    if i%10 == 8:
        count += 1

print(count)

2018/01/29 22:52

김우재

print(sum([str(x).count('8') for x in range(10000)]))

2018/01/29 23:17

김우재

package countingEight;

import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;

public class CountingEight {

    private int getEight(int n) {
        int count = 0;

        for (int i = 0; i < n; i++) {
            String str = Integer.toString(i);

            for (int j = 0; j < str.length(); j++)
                if (str.substring(j, j + 1).contains("8"))
                    count++;
        }

        return count;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        CountingEight ce = new CountingEight();

        System.out.println(ce.getEight(10000));

    }

}

2018/01/30 13:08

김치우

<script>

function _count(c) {

var i = String(c);
var _sum = 0;
for (j = 0; j < i.length; j++){
  if ( "8" == i[j] ) {
    _sum = _sum +1;
  };
};
return _sum;
  }

var _sum_overall = 0
for (i = 0; i < 10001; i++) {
  _sum_overall = _sum_overall + _count(i);
}

console.log(_sum_overall)



</script>

다들 어마 무시 하세요;;

2018/01/31 16:36

Yungbin Kim

list=[]
count=0

for i in range(10000):
    list.append('%d' %(i+1))

for i in range(len(list)):
    for j in range(len(list[i])):
        if list[i][j]=='8':
            count+=1
        else:
            continue

print count

2018/02/01 14:45

Kyung seok Oh

그냥 4천개 혹은

# 파이썬

result = 0
for t in range(1, 10001):
    for u in str(t):
        if u == '8':
            result += 1
print(result)

2018/02/04 17:09

olclocr

import java.util.*;

public class test {
    public static void main(String[] args) {
        Scanner scanf=new Scanner(System.in);
        int a=scanf.nextInt();
        String s="";
        int cnt=0;
        for(int i=1; i<=a; i++) {
            s=i+"";
            for(int j=0; j<s.length(); j++) {
                if((s.charAt(j)+"").equals("8")) {
                    cnt=cnt+1;
                }
            }
        }
        System.out.println(cnt);
    }

}

2018/02/06 01:21

즈스크

n = int(input("범위를 입력하시오: "))
result = 0
for i in range(1,n+1):
    a = list(str(i))
    for j in range(len(a)):
        if a[j] == '8':
            result += 1
print(result)

2018/02/06 10:09

김동하

total = 0

def test(num):
    cnt = 0
    for c in str(num):
        if int(c) == 8:
            cnt += 1
    return cnt


for i in range(1, 10000):
    total += test(i)

print(total)

2018/02/06 19:14

ohmazing5

#include <iostream>
#define SIZE 10000

using namespace std;
void save(int* arr,int num);
int main()
{
    int arr[4] = {0};
    int sum = 0;

    for(int i=1;i<SIZE;i++) 
    {
        save(arr,i);

        for(int j=0;j<4;j++)
        {
            if(arr[j] == 8) sum++;
        }
    }

    cout << "8의 개수 :" << sum << endl; 
    return 0;
}

void save(int* arr,int num)
{

    int j=1000;
    for(int i=3;i>=0;i--)
    {
        arr[i] = num/j;
        num%=j;
        j/=10;
    }

}


2018/02/06 20:36

이승헌

print(str(list(range(10000))).count('8'))
print(sum(str(x).count('8') for x in range(10000)))

2018/02/10 09:05

추천은 다 읽음

include

int main(){ int i=1; int cnt=0; int num; while(i<10000){ // 범위 내 8 카운트 // 자릿수 분리 num=i; while(num!=0){ if(num%10==8) cnt++; num/=10; } i++; } printf("%d",cnt); }```{.cpp}

```

2018/02/10 16:16

gudrhrehd123

r로 풀이 하였습니다.

a <- unlist(str_split(as.character(c(1:10000)),''))
sum(a == '8')

2018/02/13 17:32

Job Kang

def eight():

    n=input('range:')
    a=range(1,n+1)
    temp=[]

    for i in a:
        for j in (str(i)):
            temp.append(j)
    print temp.count('8')

answer:4000

2018/02/14 16:59

Da ne

ans=0
for k in range(1,10001):
    ans+=str(k).count('8')

print(ans)

2018/02/17 06:51

D B

def count8(n):
    count = 0
    for i in range(1,n+1):
        if '8' in str(i):
            count += sum(str(i)[j] == '8' for j in range(0,len(str(i))))
    return count
count8(10000)

2018/02/22 20:06

맹재환

public class eightSum {
    final private int number = 8;
    private int sum = 0;

    public int SumEight() {
        for(int i = 1; i <= 10000; i++) {
            String str = i + "";
            for(int j = 0; j < str.length(); j++) {
                if(Integer.parseInt(str.charAt(j)+"") == number) {
                    sum++;
                }
            }
        }
        return sum;
    }
}

2018/02/26 16:26

초초보

str(list(range(1,10001))).count('8')

2018/02/28 15:21

코끼리식당

자바입니다!

package CodingDojang;

import java.util.*;

public class CountEight {
    static final int MAX = 10000;


    public static void main(String args[]) {
        Scanner scn = new Scanner(System.in);
        String All = "";
        String[] splitedAll;
        int numOfEight;

        for(int i = 1; i <= MAX; i++) {
            All += i;
        }

        splitedAll = All.split("8");
        numOfEight = splitedAll.length - 1; //문자열 변수 All에서 맨 앞 문자와 맨 뒤 문자가 '8'이 아닌경우에만 사용 가능, 문제
                                                      에서 맨 앞 문자는 1, 맨뒤 문자는 10000의 0

        System.out.println(numOfEight);
        scn.close();
    }
}

2018/03/03 12:27

sangw0804


public class Cnt8 {

    public static void main(String[] args) {
        int cnt = 0;
        int a,b,c,d;
        for (int i = 1; i < 10000; i++) {
            a = i/1000;
            b = (i%1000)/100;
            c = ((i%1000)%100)/10;
            d = ((i%1000)%100)%10;
            if (a == 8)
                cnt++;
            if (b == 8)
                cnt++;
            if (c == 8)
                cnt++;
            if (d == 8)
                cnt++;
        }
        System.out.println("Answer is " + cnt);
    }
}

2018/03/06 18:00

강성민

public class Counting {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int count = 0;

        for(int i=1; i<=10000 ;i++ ){

            Integer number = new Integer(i);

            String numberString = number.toString();

            int n= 0;

            while(n < numberString.length()){
                char c = numberString.charAt(n);
                if(c == '8'){
                    count++;
                }
                n++;
            }

        }

        System.out.println(count);

    }

}

4000

2018/03/13 23:47

김태훈

print(len(list(int(x) for numbers in range(1, 10000) for x in str(numbers) if int(x) == 8)))

Python 3이고요 최근에 배운 list comprehension을 사용했습니다

2018/03/15 00:05

myyh2357

Swift로 해봤습니다. 백만까지 높여서 테스트를 해보니, 역시 문자열 변환없는 첫번째 방식이 압도적으로 빠르네요.

import Foundation
let maxNumber = 1000000
let sw1 = DispatchTime.now()

// -----------------------------------
// Implementation 1 - String 변환 없음
// -----------------------------------
var count1 = 0
for i in 1...maxNumber {
    var number = i
    while(number > 0) {
        if number % 10 == 8 {
            count1 += 1
        }
        number /= 10
    }
}
print (count1)

let sw2 = DispatchTime.now()
// -----------------------------------
// Implementation 2 - String으로 변환
// -----------------------------------
var count2 = 0
for i in 1...maxNumber {
    let numberString = String(i)
    for letter in numberString {
        if letter == "8" {
            count2 += 1
        }
    }
}

print(count2)

let sw3 = DispatchTime.now()
// -----------------------------------
// Implementation 3 - String으로 변환 - Variation 1
// -----------------------------------
var count3 = 0
for i in 1...maxNumber {
    let numberString = String(i)
    count3 += String(numberString.filter {$0 == "8"}).count
}

print(count3)

let sw4 = DispatchTime.now()
// -----------------------------------
// Implementation 4 - String으로 변환 - Variation 2
// -----------------------------------
var count4 = 0
for i in 1...maxNumber {
    let numberString = String(i)
    _ = numberString.filter {if $0 == "8" {count4 += 1}; return $0 == "8"}
}

print(count4)

let sw5 = DispatchTime.now()
let elappsed1 = Double(sw2.uptimeNanoseconds - sw1.uptimeNanoseconds) / 1_000_000_000
print ("Elappsed 1 : \(elappsed1) seconds")
let elappsed2 = Double(sw3.uptimeNanoseconds - sw2.uptimeNanoseconds) / 1_000_000_000
print ("Elappsed 2 : \(elappsed2) seconds")
let elappsed3 = Double(sw4.uptimeNanoseconds - sw3.uptimeNanoseconds) / 1_000_000_000
print ("Elappsed 3 : \(elappsed3) seconds")
let elappsed4 = Double(sw5.uptimeNanoseconds - sw4.uptimeNanoseconds) / 1_000_000_000
print ("Elappsed 4 : \(elappsed4) seconds")

2018/03/18 04:14

졸린하마

result=0
for i in range(1,10001):
    result+=list(str(i)).count('8')
print(result)

2018/03/18 04:15

python

  1 #include <stdio.h>
  2
  3 int main(void) {
  4
  5     int dx;
  6     int att;
  7     int a, b, c, d, e;
  8     for (int dx = 0; dx < 10000; ++dx) {
  9
 10         a = dx/10000;
 11         b = dx/1000 - a*10;
 12         c = dx/100 - a*100 - b*10;
 13         d = dx/10 - a*1000 - b*100 - c*10;
 14         e = dx - a *10000 - b*1000 - c*100 - d*10;
 15         switch (a)
 16         case  8 :
 17                att++;
 18         switch (b)
 19         case  8 :
 20                att++;
 21         switch (c)
 22         case  8 :
 23                att++;
 24         switch (d)
 25         case  8 :
 26                att++;
 27         switch (e)
 28         case  8 :
 29                att++;
 30
 31     }
 32
 33     printf("%d", att);
 34
 35     return 0;
 36 }

c언어 너무 어려워요..ㅠㅠㅠㅠㅠ

2018/03/20 12:37

올빼미

python 3.6.1

count = 0
for num in range(1, 10001):
    for i in range(0, len(str(num))):
        if str(num)[i] == '8':
            count += 1
print(count)

2018/03/24 15:54

최상혁

public class Goo{
 public static void main(String[] args){
  int i,j;
  int total1 = 0;

  for(i=0;i<10000;i++){
   int num1 = (i+1);
   String input1 = Integer.toString(i+1);
   int n = input1.length();
   for(j=0;j<n;j++){
    if(num1 % 10 == 8)
     total1 +=1;
    else;
    num1 = num1/10;
   }
  }

  System.out.print("8은 총 " + total1 + "개입니다.");
 }
}

2018/03/24 20:00

배혜민

JAVA 입니다

``````{.java} public static void checkNumber() { int count = 0; int chkNum = 0; int mok = 0;

for(int i = 0; i < 10000; i++) {
    mok = i;

    while(mok != 0) {
        chkNum = mok % 10;
        mok = mok / 10;

        if(chkNuM == 8) {
            count++;
        }
    }
}

System.out.println("checkEightCount : " + count);

} ```

2018/03/27 09:57

박정진

def counter(a,b) :
    return ''.join(map(str,range(a,b+1))).count(str(8))

print(counter(1,10000))

2018/03/27 17:06

yijeong

public static int numCountCheck(String num){
        String check=num;
        int count=0;
        for(int i=1; i<=10000; i++){
            check = i+"";
            for(int j=0; j<check.length(); j++){

                if(j+1<=check.length()){
                    if(check.substring(j, j+1).equals(num)){
                        count++;
                    }   
                }

            }
        }
        return count;
    }

2018/03/28 11:35

김준기

print(str(list(range(10000))).count('8'))

2018/03/28 14:49

재즐보프

count = 0
for i in range(10001):
    for j in str(i):
        if j == str(8):
            count = count + 1
print(count)

2018/03/31 12:20

최성범

a=str(list(range(1,10000)))
a.count('8')

2018/04/05 02:26

danbi


public class Test {
    private int cnt;

    public Test(){
        cnt=0;
    }

    public void countEight(String input) {
        for(int i=0; i<input.length(); i++){
            if(input.charAt(i)=='8') cnt++;
        }
    }

    public static void main(String[] args) {
        Test test = new Test();
        for(int i=1; i<=10000; i++){
            test.countEight(Integer.toString(i));
        }
        System.out.println(test.cnt);
    }
}

2018/04/05 22:51

이호영

public class loop2 
{
    public static void main(String[] args) 
    {
        int a = 0;
        StringBuilder s = new StringBuilder();

        for(int i = 1; i <= 10000; i++){
            s.append(i);
        }

        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == '8')
                a++;
        }
        System.out.println(cnt);
    }

}

2018/04/09 19:19

聂金鹏

"""
author: Kenny Jeon
date: 04/09/2018
"""


def func():
    cnt = 0
    # declare 8 count variable
    for num in range(1, 10001, 1):
        digits = str(num)
        # convert num to string

        for digit in digits:
            if int(digit) == 8:
                cnt += 1
        # check 8 digit in digits
    return cnt


if __name__ == "__main__":
    result = func()
    print(result)

2018/04/09 20:03

Kenny Jeon

def eight():
    count = 0
    i=1
    while i < 10001:
        a = str(i)
        for j in range(0, len(a)):
            if a[j] == '8':
                count+=1
        i+=1
    return count

print(eight())

2018/04/13 23:53

KangSan Jeon

n,x = str(input("수를 입력하세요")),0
for o in range(1,10001):
       o = list(str(o))
       x += o.count(n)
print(x)

2018/04/14 19:31

김영성

#include<iostream>
using namespace std;

int solution()
{
    int num = 1;

    int remain = 0, reauq, sum = 0;
    int count = 0;
    while (num != 10000)
    {
        reauq = num;
        num++;
        while (reauq != 0)              
        {
            remain = reauq % 10;            
            reauq /= 10;                
            if (remain == 8)
                count++;
        }
    }
    return count;
}
int main()
{
    cout << solution() << endl;
}

2018/04/16 22:40

Jun ki Kim

count = 0
for i in range(1,10001):
    for j in str(i):
        if j == '8':
            count += 1

2018/04/22 00:08

Mark

그외에 정규표현식으로 해결이 가능할 듯 합니다만..

import java.util.stream.IntStream;

/**
 * @author Kimseongsu
 * @see http://codingdojang.com/scode/393
 */
public class Problem393 {

    static final int MAX = 10000;

    public static void main(String[] args) {
        int count = IntStream.rangeClosed(1, MAX)
            .mapToObj(n -> String.valueOf(n))   // string으로 변환
            .mapToInt(s -> (int)s.chars().filter(c -> c == '8').count())    // char == '8'인 개수
            .sum();

        System.out.println(count);
    }

}

2018/04/25 18:11

Seongsu Kim

lst = []
for i in range(1,10001) :
    lst.append(i)
print(str(lst).count('8'))

2018/04/26 00:47

sungjune

lst = []
for i in range(1,10001) :
    lst.append(i)
print(str(lst).count('8'))

2018/04/26 00:48

sungjune

옮기며 배우는 중입니다.

        // 1~10000 8의 개수
        public void Test2()
        {
            int cnt = Enumerable.Range(1, 10000).Sum(i => i.ToString().Count(j => j == '8'));
            Console.WriteLine("1~10000 수 중 8의 개수 : {0}", cnt.ToString());
        }

        // 1~10000 8의 개수
        public void Test3()
        {
            string strNum;
            int iCnt = 0;
            for (int i = 1; i <= 10000; i++)
            {
                strNum = i.ToString();

                foreach (char f in strNum) if (f == '8') iCnt++;
            }
            Console.WriteLine("1~10000 수 중 8의 개수 : {0}", iCnt.ToString());
        }

2018/04/26 16:36

비트에이스

public class CountingEight {
    public static void main(String[] args) {
        for (int i=0; i<=10000; i++){
            searchEight(i);
        }
        System.out.println("1에서 10,000 사이에 존재하는 8의 개수는? "+count);
    }
    private static int count = 0;
    public static void searchEight(int num){
        if (num%10==8) count++; 
        if (num>10) searchEight(num/10);
    }
}

2018/04/30 15:13

배혁남

public static void main(String[] args) { int cnt = 0; for (int i=1; i<=10000; i++) { int a = i % 10; // 1의 자리 int b = i/10 % 10; // 10의 자리 int c = i/100 % 10; // 100의 자리 int d = i/1000 % 10; // 1000의 자리 if(a == 8) cnt++; if(b == 8) cnt++; if(c == 8) cnt++; if(d == 8) cnt++; } System.out.println(cnt); } } // 자바입니다. 다른 분들 코드 굉장하네요

2018/05/03 10:06

정몽준

public class Practice{ public static void main(String[] args){

    int count=0;

    for(int i=1;i<=10000;i++){
        if(i/1000==8)   count++;
        if((i/100)%10==8)   count++;
        if((i/10)%10==8)    count++;
        if(i%10==8) count++;
    }

    System.out.print(count);

}

}

2018/05/05 04:55

장하림

def p393():
    print(sum(str(x).count('8') for x in range(1,10001)))
    print("".join(str(i) for i in range(1,10001)).count('8'))
    print(str(list(range(1, 10001))).count('8'))


#####################################
if __name__ == "__main__":
    p393()

2018/05/08 23:13

guruchun

def eightselector(x):
    result = 0
    if x // 1000 == 8: result += 1
    if (x % 1000) // 100 == 8: result += 1
    if (x % 100) // 10 == 8: result += 1
    if (x % 10) == 8: result += 1
    return result

print(sum(list(eightselector(n) for n in range(10000))))

아름다운 풀이들 부럽네요

2018/05/09 00:02

김산양

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int Counting(int);

int main() {

    int i, count;
    count = 0;

    for (i = 1; i <= 10000; i++) {
        count += Counting(i);
    }

    printf("%d\n", count);
    //getch();
    return 0;
}

int Counting(int num) {
    char num_ch[6];
    int count, length, i;
    sprintf(num_ch,"%d", num);
    length = strlen(num_ch);
    count = 0;

    for (i = 0; i < length; i++) {
        if (num_ch[i] == '8') {
            count++;
        }
    }
    return count;
}

2018/05/18 13:37

송준호

count = 0
for i in range(1,10001):
    count += list(str(i)).count('8')

print (count)

2018/05/22 23:11

김정현


public class Include8 {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 1; i < 10001; i++) {
            for (int j = 0; j < (i + "").length(); j++) {
                char[] at = (i + "").toCharArray();
                if (at[j] == '8') {
                    count++;
                }
            }
        }
        System.out.println(count);
    }
}

2018/05/24 19:34

김지훈

def counting(number):
    cnt = 0
    tmp = str(number)
    for i in tmp:
        if int(i) == 8:
            cnt += 1
    return cnt


res = 0
for i in range(10001):
    res += counting(i)

print(res)

2018/05/28 19:46

bnewkk

let sumOfEight = 0;

for(let i = 1;i<10000;i++)
{
    sumOfEight += String(i).replace(/[^8]/g,"").length;
}

console.log(sumOfEight);

2018/05/29 22:52

elle0715

data=[str(x).count('8') for x in range(1,10000)]
print(sum(data))

2018/05/31 00:52

조성은

s=0; for i in range(1,10000): s+=str(i).count('8'); print(s); out:4000;

2018/05/31 19:56

Gerrad kim

Python

print(sum(str(i).count("8") for i in range(1, 10001)))

2018/06/01 13:59

Taesoo Kim

#include <stdio.h>

int main()
{
    int i;
    int sum = 0;
    for(i=1;i<=10000;i++)
    {
        if(i%10 == 8)
            sum++;
        if((i%100)/10 == 8)
            sum++;
        if((i%1000)/100 == 8)
            sum++;
        if(i/1000 == 8)
            sum++;
    }
    printf("%d",sum);
    return 0;
}

2018/06/17 21:15

나윤바보멍청이

tm = " "
for i in range(0,10000):
    tm =  tm + str(i)
tm    
import re
p = re.compile(r'8')
m = p.findall(tm)
len(m)

출력값 : 4000

2018/06/19 10:37

프로젝트1교통약자석

#include <iostream>

using namespace std;

int main() {
    int count = 0;
    for (int i = 1; i <= 10000; i++) {
        int num = 0;
        if (i % 1000==0) {
            num = i / 1000;
            if (num / 8 == 1) {
                count++;
            }
                num = i - (1000 * (i / 1000));
        }
        if (i % 100 == 0) {
            int num = i / 100;
            if (num / 8 == 1) {
                count++;
            }
            num = i - (100 * (i / 100));
        }
        if (i % 10 == 0) {
            int num = i / 10;
            if (num / 8 == 1) {
                count++;
            }
            num = i - (10 * (i / 10));
        }

        if (i % 1 == 0) {
            int num = i ;
            if (num / 8 == 1) {
                count++;
            }
            num = i - (1 * (i / 1));
        }

    }

    cout << count<<"\n";


    return 0;
}

2018/06/20 15:17

노명준

def eight_count():
    n = 0
    for i in range(1, 10001):
        if str(8) in str(i):
            n += str(i).count(str(8))
    print(n)

2018/06/24 20:38

co_de_ing

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int sum = 0;
        Enumerable.Range(1, 10000).ToList().ForEach(e => sum += e.ToString().Count(n => n == '8'));
        Console.WriteLine(sum);
    }
}

2018/06/29 12:51

mohenjo

counter = 0 for num in range(1,10001): str_num = str(num) for i in range(0,len(str_num)): #print(len(str_num)) if int(str_num[i]) == 8: counter+=1 print(counter)

2018/06/30 17:01

김용준

def eight_counter(n):
    count = 0
    for i in str(n):
        if i == "8":
            count += 1
    return count

sum = 0
for i in range(1,10001):
    sum += eight_counter(i)

print(sum)

2018/07/03 02:41

WJ K

#include <stdio.h>
#include <string.h>

#define MAX 6

int main(void)
{
    int i;
    int Num = 0;
    int cnt = 0;
    char buf[MAX];

    while(Num <= 10000){
        i = 0;
        buf[MAX] = {0};
        sprintf(buf, "%d", Num);
        while(buf[i] != '\0'){          
            if(buf[i] == '8'){
                cnt++;
            }
            i++;
        }
        Num++;
    }
    printf("cnt : %d\n", cnt);
    return 0;
}

4000 나왔네요

2018/07/06 16:42

김엽기

Python

first = 1
last = 10000
count = 0

for i in range(first, last + 1):
    for j in str(i):
        if int(j) == 8:
            count += 1

print(count)

4000

2018/07/08 04:32

eun

eight = 0
for x in range(1, 10001):
    popList = [int(d) for d in str(x)]
    while popList:
        if popList.pop() == 8:
            eight += 1
print(eight)

4000

2018/07/10 13:57

kkyu

        static void Main(string[] args)
        {
            int nCnt, nSum = 0;

            string[] mData = new string[10000];

            for (int i = 0; i < 10000; i++)
            {
                mData[i] = i.ToString();
            }

            for (int k = 0; k < mData.Length; k++)
            {
                nCnt = mData[k].Length;

                for (int m = 0; m < nCnt; m++)
                {
                    if(mData[k].Substring(m,1) == "8")
                    {
                        nSum++;
                    }
                }
            }
            Console.WriteLine(nSum.ToString());
        }

2018/07/12 00:32

정태식

eightnum=0
for i in range(1,10001):
    stri=str(i)
    a=list(stri)
    for k in a:
        if k=="8":
            eightnum+=1
print(eightnum)

2018/07/12 15:21

Jungmin Lee

print( ''.join([str(i) for i in range(1,10001)]).count('8') )

2018/07/12 20:39

Creator

def counting(num):
    count_8 = 0
    for i in range(1, num + 1):
        a = str(i)
        for j in a:
            if(j == '8'):
                count_8 += 1
    return count_8

2018/07/17 18:16

시간의마법

n = 315
n_string = str(n)
result = 0

if len(n_string) == 1:
    for i in range(n,10000):
        i_string = str(i)
        for j in range(len(i_string)):
            if i_string[j] == n_string:
                result+=1

else:
    for i in range(n,10000):
        i_string = str(i)
        start = 0
        end = len(n_string)
        for j in range(len(i_string)+1-len(n_string)):
            if i_string[start:end] == n_string:
                result+=1
            start+=1
            end+=1
print(result)

2018/07/17 20:54

서완길 (선인장물주기)

180730~ kakao 알고리즘 산책

count = 0
for i in range(1, 10001):
    kick = str(i)
    for j in range(0, len(kick)):
        if kick[j:j+1] == "8":
            count = count + 1
print(count)

2018/07/31 12:30

이용재

C 언어

#include <stdio.h>

int count = 0;
int i = 0 ;

int main()
{

    while( i <10000 )
    {
        if( ( i / 1000) == 8 )        // 천의 자리
            count += 1;
        if( ( i % 1000 ) / 100 == 8 )   // 백의 자리
            count += 1;
        if( ( i % 100) / 10 == 8 )     // 십의 자리
            count += 1;
        if( ( i % 10 ) == 8 )         //일의 자리
            count += 1;
        i++;
    }

    printf("%d", count);
}

2018/07/31 23:49

Jaeju An

//c언어 8이라는 숫자가 총 몇번 나오는지를 확인하는것이기떄문에 모든수를 배열에 저장해버린다.

#include<stdio.h>

int main()
{
    int i,j=12;
    int arr[50000] = {0, };
    int cnt =0;
    int count = 0;

    for(j=1; j<=10000; j++)
    {
        i = j;

        while(i>0)
        {
            arr[cnt] = i%10;
            //printf("%d", arr[cnt]);
            i = i/10;
            cnt++;
        }
    }

    for(i=0; i<cnt; i++)
    {
        if(arr[i]==8)
        {
            count++;
        }
    }
    printf("%d", count);    
}

2018/08/08 14:19

이우경

a = ""

for i in range(1, 10001):
    a = a + str(i)

count = a.count('8')

print("1~10000까지의 8이라는 숫자가 총 %d 번나옵니다." %count)

'''
입력받은 숫자의 갯수가 총몇번 나오는지알려줌
a = ""

number = int(input("1~ 10000 까지의 입력한 숫자가 총몇번 나오는지 알려주는 프로그램입니다. 숫자 입력 : "))

while True:
    if 0<=number and number<=9:
        break;
    else:
        number = int(input("1~9까지의 범위의 숫자를 입력하세요 : "))

for i in range(1, 10001):
    a = a + str(i)


count = a.count(str(number))

print("1~10000까지의 %d 라는 숫자가 %d번 나옵니다." %(number, count))
'''

2018/08/10 07:11

이우경

public class EightCount {
    public static void main(String[] args) {
        int count = 0;
        for(int i=0; i<10000; i++) {
            for(int j=i; j>0; j/=10) {
                if(j%10 == 8) {
                    count++;
                }
            }
        }

        System.out.println("Count : " + count);
    }
}

2018/08/13 23:36

송보근

# .count를 생각을 못 했었네요.....

r = 0
for i in range(1,10001):
    for a in str(i):
        if int(a) == 8:
            r += 1
print(r)

2018/08/16 20:23

김건우


public class test {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 1; i <= 10000; i++)
            for (int j = 0; j < (i + "").length(); j++)
                count += (i + "").charAt(j) == '8' ? 1 : 0;
        System.out.println(count);
    }
}

2018/08/18 21:05

김성우

print(str(list(range(1,10001))).count('8')) 파이썬 3.7 ㅎ 이거밖에 모르겠당

2018/08/19 18:56

Youngstone422

count=0

for i in range(10000):
    n=str(i+1)

    for j in n:
        if int(j)==8:
            count+=1    

print(count)

2018/08/22 01:59

JW Yoo

cnt = 0

for n in range(1, 10001):
    for m in str(n):
        if int(m) == 8:
            cnt += 1

print(cnt)

2018/08/22 19:12

이충각

Ruby

(1..10000).to_a.map do |i| i.to_s.split('') end.flatten.select do |i| i == "8" end.length

2018/08/24 11:34

아뇩다라삼먁삼보리

print(str(list(range(1,10001))).count('8'))

2018/08/27 21:58

전형진

res=0

for i in range(1,10001):
    res+=str(i).count('8')

print(res)

2018/09/03 15:36

전형진

count = 0

for i in range(1, 10001) :
    for k in str(i) :
        if k == '8' :
            count += 1

print(count)

2018/09/13 02:02

이수현

    public static void main(String[] args) {

        int sum = 0;
        for(int i=1 ; i <= 10000 ; i++) {
            sum += checkCount(i);
        }

        System.out.println(sum);
    }


    public static int checkCount(int number) {

        int cnt = 0;
        //int res = number;

        if(number >= 1000) {
            if(number /1000 == 8) cnt++;
            number %= 1000;
        }

        if(number >= 100) {
            if(number /100 == 8) cnt++;
            number %= 100;
        }
        if(number >= 10) {
            if(number /10 == 8) cnt++;
            number %= 10;
        }

        if(number >= 1) {
            if(number /1 == 8) cnt++;
        }

        return cnt;
    }

2018/09/14 12:20

강창열

#include <stdio.h>

int main(){
    int i,array_8[10000],sum=0;

    for(i=0;i<10000;i++)
        array_8[i]=i+1;
    for(i=0;i<10000;i++)
        sum+=counter(array_8[i]);

    printf("%d",sum);

    return 0;
}

int counter(n){
    int n1=n/1000,n2=(n%1000)/100,n3=(n%100)/10,n4=n%10,count=0;

    if (n1==8) count++;
    if (n2==8) count++;
    if (n3==8) count++;
    if (n4==8) count++;

    return count;
}

c언어... 멍청하게 푼건가...

2018/09/25 01:19

subzero_99

public class EightLetterCount {
    public static void main(String[] args) {
        int cnt = 0;
        int[] arr = new int[4];

        for(int i = 1; i < 10000; i++) {

            arr[0] = i/1000;
            arr[1] = i/100 - arr[0]*10;
            arr[2] = i/10 - arr[1]*10 - arr[0]*100;
            arr[3] = i - arr[2]*10 - arr[1]*100 - arr[0]*1000;

            for(int j = 0; j < arr.length; j++){
                if(arr[j] == 8) {
                    cnt++;

                }
            }   
        }
        System.out.print("cnt: " + cnt);
        System.out.println();
    }
}

cnt: 4000

2018/10/01 14:31

Ju Wonjin

이 문제엔 이 방법이 제일 좋은거 같습니다.

#include <iostream>
using namespace std;

int main() {
    int InputSize, TargetNumber;
    int i, j,count = 0;

    cout << "Number Size : 1 ~ ";
    cin >> InputSize;
    cout << "Target Number : ";
    cin >> TargetNumber;

    for (i = 1; i < InputSize; ++i) {
        for (j = i; j > 0; j /= 10) {
            if (j % 10 == TargetNumber)
                ++count;
        }
    }
    cout << "count : " << count << endl;

    //system("pause");
    return 0;
}

동적할당으로도 풀어봤지만 이 문제에선 큰 영향이 없는거 같습니다.

#include <iostream>
#include <time.h>
using namespace std;

int* Dictionary;
int TargetNumber;


int calculateCount(int i) {
    if (Dictionary[i] != -1)
        return Dictionary[i];

    if (i < 10) {
        if (i == TargetNumber) {
            Dictionary[i] = 1;
            return 1;
        }

        else {
            Dictionary[i] = 0;
            return 0;
        }
    }

    if (Dictionary[i / 10] != -1) {
        Dictionary[i] = Dictionary[i % 10] + Dictionary[i / 10];
        return Dictionary[i];
    }
    else {
        Dictionary[i] = Dictionary[i % 10] + calculateCount(i / 10);
        return Dictionary[i];
    }
}


int main() {
    clock_t begin, end;
    begin = clock();
    {
        int InputSize;
        int i = 0, result = 0;

        cout << "Number Size : 1 ~ ";
        cin >> InputSize;
        cout << "Target Number : ";
        cin >> TargetNumber;

        InputSize += 1;
        Dictionary = new int[InputSize];
        memset(Dictionary, -1, sizeof(int)*InputSize); // initialize

        int maxcount = result;

        for (i; i < InputSize; ++i) {
            result += calculateCount(i);

            if (result != maxcount) {
                //cout << "i : " << i << " / result : " << result << endl;
                maxcount = result;
            }
        }

        cout << "result : " << result << endl;

        free(Dictionary);

    }
    end = clock();
    cout << "Time : " << (end - begin) / CLOCKS_PER_SEC << endl; 

    system("pause");
    return 0;
}

2018/10/01 18:15

박상준

num_list = []

for i in range(1, 10001):
    num_list.append(i)

num8 = 0

for l in num_list:
    for m in str(l):
        if int(m) == 8:
            num8 += 1

print(num8)

2018/10/05 20:00

농창

public class counteight {

public static void main(String[] args) {
    int i = 1;

    int sum = 0;

    while(i<=10000) {
        String num = Integer.toString(i);

        for(int j=0; j<num.length();j++) {
            if(num.charAt(j)=='8') {
                sum += 1;
            }
        }

        ++i;
    }

    System.out.println(sum);
}

}


2018/10/08 15:40

김찬영

0000부터 9999까지 총 경우는 10000가지이고 여기에 한 경우당 숫자가 4개 있으므로 총 나오는 숫자의 개수는 40000개 입니다. 그런데 0부터 9까지의 숫자는 나오는 경우가 각각 같아야 합니다. 그래서 40000을 10으로 나눈 4000이 숫자 하나당 나오는 개수라는 것을 알 수 있습니다. 그래서 8이 나오는 개수 또한 4000개 입니다.

2018/10/15 13:04

김재웅

public class Answer {

    public static void main(String[] args) {
        int count = 0;
        List<String> list = new ArrayList<>();
        for(int i=1; i<10000; i++) {
            String s_num = String.valueOf(i);
            list.add(s_num);
        }
         String[] s = list.toArray(new String[list.size()]);

         for(int i=0; i<s.length; i++) {
             if(s[i].length() ==1 && s[i].equals("8"))
                count++;
             else if(s[i].length()!=1){
                 String[] word = s[i].split("");

                 for(int j=0; j<word.length; j++) {
                     if(word[j].equals("8"))
                         count++;
                 }
             }
             else
                 continue;
         }
    System.out.println("8이 총 등장하는 수 : " + count);
    }  

}

2018/10/25 11:18

황세호

count = 0

for i in range(1,10001):
    for j in str(i):
        if j == '8':
            count += 1

print(count)

2018/10/26 11:59

이재석

public class KimSanghyeop
{
    public static void main(String[] args)
    {
        int cnt=0;

        int f1;
        int temp;

        for(f1=1;f1<10000;f1++)
        {
            temp=f1;
            while(temp!=0)
            {
                if(temp % 10 == 8)
                {
                    cnt+=1;
                }
                temp = temp /10;
            }
        }

        System.out.println(cnt);
    }
}

2018/11/01 16:16

김상협

Python

>>> sum(str(i).count('8') for i in range(10001))

코드를 조금 더 빠르게 하려면 제너레이터를 사용하면 됩니다.

>>> sum((str(i).count('8') for i in range(10001)))

2018/11/01 23:52

Spike Lee

def eight_chk() :
    # 10 이하의 숫자에서 8이 나오는 경우, 1
    cnt = 1
    for i in range(10,10001) :
        for j in range(len(str(i))-1,-1,-1):
            mok = i // pow(10,j)
            if mok == 8 :
                cnt += 1
            i = i % pow(10,j)
            if i==0 : break
    return cnt

2018/11/05 22:49

쨔이

cnt = 0

for s in range(1, 10001):
    for i in str(s):
        if i == '8':
            cnt += 1

print(cnt)


2018/11/12 21:05

그사람 남한 볼 수 있어요

# python 3.7.1

print(sum(str(x).count('8') for x in range(1, 10001)))

2018/11/13 17:42

정지환

count = 0
for i in range(10000):
    for j in str(i):
        if j=='8':
            count = count+1
print(count)

2018/11/13 19:28

문지원

#include <stdio.h>

int main(void)
{
    int n =10000;
    int sum = 0;
    char catNum='8';
    int i,j;
    char check[5]={};

    for(i=1;i<(n+1);i++)
    {   
        sprintf(check,"%d",i);
        for(j=0;j<5;j++)
        {   
            if(check[j]==catNum)
                sum++;
        }   
    }   

    printf("The Number of %c is [%d] in 1...%d\n",catNum,sum,n);

    return 0;
}

2018/11/15 12:33

Lee

count=0
for i in range(1,10001,1):
    a=str(i).count('8')
    count+=a

2018/11/23 11:15

임채원

#findEight.py

num = range(1,1000)

line=""
for i in num:
    line = line + str(i)

print(line.count("8"))

2018/11/27 16:52

EunKyung Jung

#findEight.py

num = range(1,10000)

line = " "
for i in num:
    line = line + str(i)

print(line)
print(line.count("8"))

2018/11/27 16:56

EunKyung Jung

def solution
  (1..10000).inject(0){|c, n| c+=n.digits.count(8)}
end

p solution

2018/12/04 14:06

zzulu

def solution():
    return sum([str(n).count('8') for n in range(1, 10001)])

print(solution())

2018/12/04 14:46

zzulu


n='0'
result=0
while int(n) <10000 :

    n=str(int(n)+1)

    for i in range(len(n)):
        if n[i] =='8':
            result +=1    
print(result)

2018/12/05 13:42

S.H

n=10000;%1~10000
k=8;%8의 개수
h=ceil(log10(n));%10^(h-1)<n<=10^h
count=0;
for i=1:n
    s(1)=i;
    for j=1:h-1
        m(j)=floor(s(j)/10^(h-j));%10^n 으로 나누기
        s(j+1)=s(j)-(10^(h-j))*m(j);
    end
    m(h)=s(h);
    for a=1:h
        if m(a)==8
            count=count+1;
        end
    end
end
fprintf('1~%d 까지의 8의 개수 : %d\n',n,count);

2018/12/05 14:45

GammaKnight

문자열 관련 함수를 사용하지 않고 풀어보았습니다 - GammaKnight, 2018/12/05 14:46
#include <iostream>
using namespace std;

int main()
{
    int c=0,t=0,mx=10000;
    for(int i=0;i<mx;i++){
        t=i;
        while(t){
            if(t%10 == 8) c++;
            t/=10;
        }
    }
    cout<<c;
}

2018/12/16 12:05

김한길

word = ''

for x in range(1, 10001):
    word = word + str(x)

num1 = len(word)
spl_eight = word.split('8')

word2 = ''

for y in spl_eight:
    word2 = word2 + y

num2 = len(word2)

print(num1 - num2)

2018/12/16 19:42

김형선

count = 0 for digit in range(1, 10001): for s in str(digit): if(s == "8"): count += 1 print(count)

2019/01/02 17:31

선선모

print(sum(sum(int(x)//8 for x in str(i) if x == '8') for i in range(1,10001)))

답 : 4000

2019/01/03 18:44

판다네밥상

print((''.join(str(i) for i in range(1,10000)).count('8')))

2019/01/04 00:30

lucky1to10

namespace codingdojang__
{
    class Program
    {
        static void Main(string[] args)
        {
            int total = 0;

            for (int i = 1; i < 10000; i++)
            {
                int temp = i;

                while (temp != 0)
                {
                    if (temp % 10 == 8)
                    {
                        total++;

                        temp /= 10;
                    }
                    else
                    {
                        temp /= 10;
                    }

                }
            }

            Console.WriteLine(total);
        }
    }
}

2019/01/08 10:26

bat

public class counts {
    private static int count(int n)
    {
        int cnt = 0;
        while (n > 0)
        {
            if (n % 10 == 8)
            {
                cnt++;
            }
            n /= 10;
        }
        return cnt;
    }
    public static void main(String[] args)
    {
        int sum = 0;
        for (int i = 1; i <= 10000; i++)
        {
            sum += count(i);
        }
        System.out.println(sum);
    }
}

2019/01/08 20:19

김민지

print (str([x for x in range(1,10001)]).count('8'))

Python 3 입니다

2019/01/16 22:39

carcassi

public class Ex02 {
    public static int func(int num) {
        int cnt = 0;

        while (true) {
            if (num % 10 == 8) {
                cnt++;
            }

            num = num / 10;

            if (num / 10 == 0 && num % 10 == 0) {
                break;
            }
        }

        return cnt;
    }

    public static void main(String[] args) {
        int start = 1;
        int end = 10000;

        int sum = 0;

        for (int i = start; i <= end; i++) {
            sum += func(i);
        }

        System.out.println(start + "부터 " + end + "까지 8의 개수는 " + sum + "개 입니다.");
    }
}

2019/01/17 14:14

kiiii

```{.cpp}

include

include

using namespace std;

int main(void) { int cnt = 0; string sentence; for (int i = 1; i < 10000; i++) { sentence = to_string(i); for (int i = 0; i < sentence.length(); i++) { if (sentence[i] == '8')cnt++; } } cout << cnt << endl; } ```//문자열로 풀어봤어요~

2019/01/18 00:23

김상범

자바입니다~ 숫자를 String 클래스로 바꿔서 했어요.. 최대한 간략하게 짜보려고 해도 아직 이정도네요 ㅠ

class SumTo10000 { public static void main(String[] args) {

    int numOf8=0;

    for(int i=8;i<=9998;i++) {
        String str = "" + i;
        for(int j=0;j<str.length();j++) {
            if (str.charAt(j)=='8') 
                ++numOf8;
        }
    }   
    System.out.println("number of 8's: " + numOf8);
}

}

2019/01/21 07:41

고요정

자바입니다~

class SumTo10000 {
    public static void main(String[] args) {

        int numOf8=0;

        for(int i=8;i<=9998;i++) {
            String str = "" + i;
            for(int j=0;j<str.length();j++) {
                if (str.charAt(j)=='8') 
                    ++numOf8;
            }
        }   
        System.out.println("number of 8's: " + numOf8);
    }
}

2019/01/21 12:30

고요정

#include <stdio.h>

int main()
{
    int num[5];
    int cnt = 0;
    for (int i = 0; i < 10001; i++)
    {
        num[0] = i / 10000;
        num[1] = i % 10000 / 1000;
        num[2] = i % 1000 / 100;
        num[3] = i % 100 / 10;
        num[4] = i % 10;

        for (int j = 0; j < 5; j++)
        {
            if (num[j] == 8)
            {
                cnt++;
            }
        }
    }
    printf("%d", cnt);
    return 0;
}

코딩 잘하시는분들이 부럽습니다

2019/01/23 02:30

김민진

total = 0
for i in range(1,10001):
    temp = list(str(i))
    total += temp.count('8')

print(total)

2019/01/23 12:12

D.H.

using namespace std;
#include <iostream>

int main ()
{
    int count =1;
    int quotient,remain;
    for (int i=0; i<10000; i++)
    {
        if (i>9)
        {
            quotient=i;
            while (quotient>9)
            {
                remain=quotient%10;
                quotient=quotient/10;
                if (remain==8)
                count++;
            }
            if (quotient==8)
            count++;
        }
    }
    cout << count << endl;
    return 0;
}

2019/01/25 05:43

류준열

$cnt = 0;
for($i=1; $i<=10000; $i++)  for($j=0; $j<strlen($i+""); $j++)  if(substr(($i+""), $j, 1) == 8)  $cnt++;
echo $cnt;

2019/01/25 12:58

김태우

print(sum([str(i).count('8') for i in range(10001)]))

2019/01/27 18:03

Roy

def FindEight(start,stop):
    return str(list(range(start,stop+1))).count('8')

print(FindEight(1,10000))

간단하게 함수형식으로~

2019/01/30 00:28

얀차

문제에서는 10000까지 8이 몇번 나오는지 구하라고 했지만 만약 15000까지 8이 몇번 나오라는지 구하라면 코딩이 필요하지 않을까요?

이런 상황에 대비해 코딩을 해보자면

start=1
upper=15000

what_digit = len(str(upper))

answer=0
for i in range(1 , what_digit): 
    str_upper = str(upper)
    answer +=  int(str_upper[:-i]) * pow(10,(i-1))

print(answer)

2019/01/30 11:02

임정섭

print(str(list(range(1,10001))).count('8'))

2019/01/30 22:46

Lapis

1000의 자리가 8인 수의 개수는 8000~8999로 1000개이다. 다르게 생각하면 8xxx에서 x가 0~9이므로 10^3=1000개 이다. 같은 방법으로 100의 자리, 10의 자리, 1의 자리가 8인 수도 각각 1000개임을 알 수 있다. 따라서 답은 4000개이다.

(근데 이걸 누가 먼저 생각했네요..)

2019/01/31 23:24

김태헌

이 이상으로 더 간결한 코드는 없는듯 하네요 print(str(list(range(1, 10001))).count('8'))

2019/02/01 14:33

조유빈

R로 작성했습니다

function1 = function(object, from, to){
  input = c()
  for(i in from:to){
    tmp = strsplit(as.character(i),"")[[1]]
    input = append(input, tmp)
  }
  count = sum(input %in% as.character(object))
  return(count)
}
function1(8,0,10000)

2019/02/02 07:38

강창구

#include<iostream>
using namespace std;

int CountEight(int num);

int CountEight(int num){
    int Cunum = 0;
    if ((num / 1000) == 8){
        ++Cunum;
    }
    if ((num / 100) % 10 == 8){
        ++Cunum;
    }
    if ((num / 10) % 10 == 8){
        ++ Cunum;
    }
    if ((num % 10) == 8){
        ++Cunum;
    }
    return Cunum;
}

int main(void){
    int sum=0;
    int sumnum = 0;
    for (int i = 1; i <= 10000; i++){
        sumnum = CountEight(i) + sumnum;
    }

    cout << sumnum << endl;

    return 0;

}

2019/02/03 12:13

박태준

num_cnt = 0
for num in range(1,10001):
    sep_nums = []
    for sep_num  in str(num):
        sep_nums.append(sep_num)
    for sep_num in sep_nums:
        if sep_num == '8':
            num_cnt += 1
print(num_cnt)

2019/02/07 15:03

현모구

public class Count8 {
    public static void main(String[] args) {
        int cnt=0;
        for(int i = 1;i<=10000;i++) {
            Integer num = i;
            String str = num.toString();
            char[] chArray  = str.toCharArray();

            for( char ch : chArray){
                 if(8==Character.getNumericValue(ch)) cnt++;
             }

        }
        System.out.println(cnt);
    }
}

2019/02/07 22:37

엄세진

public class EightCounting {
    public static void main(String[] args){
        int count = 0;

        for(int i = 0; i <= 10000; i++){
            if(i/1000 == 8)
                ++count;
            if((i/100)%10 == 8)
                ++count;
            if((i/10)%10 == 8)
                ++count;
            if(i%10 == 8)
                ++count;   
        }

        System.out.println(count);
    }
}

2019/02/07 22:57

김동수

package problem07;

public class solution {
    public static int Eight_counting(int n) {
        int count=0;
        while(n>0) {
            if(n%10==8) {
                count+=1;
                n=(n-(n%10))/10;                
            }
            else {
                n=(n-(n%10))/10;
            }           
        }
        return count;



    }

    public static void main(String[] args) {

        int count=0;
        for(int i=1; i<=10000;i++) {
            count+=Eight_counting(i);
        }
        System.out.println("1~10,000까지 숫자 8은 총 "+count+"번 나왔습니다.");
    }
}

2019/02/07 23:40

유견

let result = 0
for(let i = 1; i<=10000; i++){
  // const memory = []
  const splitted = String(i)
  for(let j = 0; j<splitted.length; j++){
    if(splitted[j] === '8')
    result += 1
  }
}
console.log(result)
//결과: 4000

2019/02/10 15:30

돌도끼

count = 1;
for i in range(11, 10001) :
    i = str(i)
    for j in range(len(i)) :
        if i[j] == '8' : count+=1
print(count)

2019/02/14 09:45

동동

count=0
for num in range(0,10000):
    num=list(str(num))
    for eight in num:
      if (eight=='8'):
          count+=1

print(count)



2019/02/14 10:06

이정헌

total = 0
for i in range(10000):
    str_i = str(i)
    count_eight = str_i.count('8')
    total += count_eight
print(total)

2019/02/14 10:36

김상민

import re
box = 0
p = re.compile('(0|1|2|3|4|5|6|7|9)')
for i in range(1,10001):
    b = str(i)
    m = p.sub('',b)
    box += len(m)
print(box)   

2019/02/16 16:58

김규묭

count=0
for i in range(1,10000):
    eight = str(i)
    count+=eight.count('8')

print(count)

2019/02/18 09:07

print(sum([1 for num in range(1, 10000 + 1) for jarisu in str(num) if jarisu == '8']))

2019/02/18 14:42

좋은나쎔

위대한 하스켈!

length. filter (=='8') . concat . map show $ [1..10000]

직관적이고 아름답습니다.

2019/02/22 19:14

Taekyung Kim

sum=0
for i in range(1,10001):
    a=str(i)
    sum+=a.count("8")
print(sum)

2019/02/26 17:34

ykleeac

cn=0
for j in [str(i) for i in range(10000) if '8' in str(i)]:
    print(j)
    for i in j:
        if i == '8':
            cn += 1
cn

2019/03/18 20:52

김동률

result = 0

for n in range(1,10000):
    kkk = 0
    for i in str(n):
        if i=='8':
            kkk+=1

    result +=kkk
print(result)

2019/03/19 15:26

한상준

count = 0
for i in range(1, 10001):
    for j in range(0, int(len(str(i)))):
        if int(str(i)[j]) == 8:
            count += 1
        else:
            pass
print(count)

2019/03/21 17:52

김성근

c언어 입니다

#include <stdio.h>
int main(){
    int num,digit,count = 0;
    for(int i=1; i<=10000;i++){
        num = i;
        while(1){
            digit = num % 10;
            if(digit==8){
                count++;
                }
            if(num>=10){
                num /= 10;
            }
            else
                break;
        }
    }
    printf("1부터 10000까지 8은 %d번 나옵니다", count);
}

2019/03/22 22:18

용 빈

한번에 답이 안나와서 과정의 내용이 맞는지 타이핑 해 보았습니다.

Analyticsstory 님 답을 참고했습니다.

print(range(1,21)) a = range(1,21) print('a:',a)

a = list(range(1,21)) print('a:',a)

a = str(list(range(1,21))) print('a:',a)

print(str(list(range(10001))).count('8'))

2019/03/23 12:21

문광경

package test;

public class test4 {

public static void main(String[] args) {
    int Cnt = 0;
    for(int i=1;i<=10000; i++) {
        int fromIndex = -1;
        String num = Integer.toString(i);
        while ((fromIndex = num.indexOf("8", fromIndex + 1)) >= 0) {
            Cnt++;
        }

    }
    System.out.println(Cnt);
}

}

2019/04/01 01:19

뇨뇨뇽


public class practice {

    public static void main(String[] args) {

            int cnt = 0;

            for (int i = 1; i < 10000; i++)
            {
                if (i % 10 == 8) cnt++;
                if (i >= 10 && i < 100)
                {
                    if(i / 10 ==8) cnt++;
                }
                else if (i >= 100 && i < 1000)
                {
                    if(i / 100 ==8) cnt++;
                    if(i / 10 % 10 == 8) cnt++;
                }
                else
                {
                    if(i / 1000 == 8) cnt++;
                    if(i / 100 % 10 == 8) cnt++;
                    if(i / 10 % 10 == 8) cnt++;
                }
            }
            System.out.println(cnt);
    }
}

2019/04/02 15:47

Albert

#include <stdio.h>

int main ()
{
    int i,j,c=0;
    int count=0;
    for(i=1;i<=10000;i++)
    {
        c=i;
        for(j=1;i>j;j*=10) 
        {
            if(c%10==8)
            {
                count++;
                c=c/10;
            }
            else
            {
                c=c/10;
            }
        }
    }

    printf("%d",count);
    return 0;
}

2019/04/05 18:27

kwon

count = []
for i in range(10000):
  k = i+1
  for j in str(k):
    if j =='8':
        count.append(1)
print(sum(count))

2019/04/08 18:52

조성철

numList=[str(i) for i in range(1,10000)]
cnt = 0
for num in numList:
    for i in range(len(num)):
        if num[i] == '8':
            cnt+=1
print(cnt)

창의력이 1도 없는 풀이입니다...ㅠㅠ```{.python}

```

2019/04/11 14:50

Chang Hwan Kim


total=0

for i in range(10000):

    nums_of_8=str(i).count('8')
    total+=nums_of_8

print(total)

2019/04/13 22:44

Choi BH

count = 0
for num in range(1,100001):
    for item in str(num):
        if item == '8':
            count += 1
print(count)

2019/04/17 02:29

Wonjin Park

for(; num<10000; num++) {
            i = num/1000;
            j = (num%1000)/100;
            k = (num%100)/10;
            l = num%10;

            if(i == 8)
                count++;
            if (j==8) {
                count++;
            }if (k==8) {
                count++;
            }if (l==8) {
                count++;
            }
        }

2019/04/29 21:37

Dopot

old func은 O(N), new) new_func은 O(1)

int old_func (int N)
{
    int cnt = 0;
    for(int i = 1 ; i <= N; ++i)
    {
        for (int j = 1; i / j > 0; j *=10) {
            if((i / j) % 10 ==8 )
                cnt++;
        }

    }
    return cnt;
}
int new_func (int N)
{
    int cnt = 0;
    for(int i = 1; N/ i > 0; i *=10)
    {
        if((N / i) % 10 <= 7)
        {
            cnt += (N / (10 * i)) * i;
        }
        else if((N / i) % 10  == 8)
        {
            cnt += (N / (10 * i)) * i + 1 + (N % i);
        }
        else
        {
            cnt += (N / (10 * i) + 1) * i;
        }
    }
    return cnt;
}

2019/05/01 13:45

이기준

ans=0
for i in range(10000):
    ans+=str(i).count('8')
print(ans)

유투브에서 재즐보프님의 영상으로 파이썬을 시작하게 되었는데, 그때의 연습문제 동영상으로 이 문제가 있었던적이 떠오릅니다. 자세히 기억이 나지는 않지만은, 그래도 어떤 방식으로 풀었는지는 대강 기억이 납니다. 그래서 그것을 직접 적용하려고 했더니만, 이미 코딩할 필요도 없이 손계산으로 풀어져버려서 어떻게 코딩을 해야하는가 고민하고 있었읍니다. 마치 수능문제에 출제되어도 이상하지 않을 난이도의 문제라 잠시 길을 잃었는데, 범위를 잘 보니, 완전탐색법을 써도 계산 횟수가 1만회 정도이기 때문에 시간이 그리 걸리지는 않을것 같아서 꽤 우직한 풀이를 하였읍니다.

2019/05/03 17:58

암살자까마귀

count = 0
for i in range(1,10000+1):
    for j in str(i):
        if int(j) == 8:
            count += 1
print(count)

2019/05/06 18:19

조관우

count=0
for i in range(1,10001):
    a="%d"%i
    for j in a:
        if j=="8":
            count+=1
print(count)

2019/05/09 19:47

donghyeok kang

count = 0
for i in range(1, 10000+1):
    s = str(i)
    for d in s:
        if d == '8':
            count += 1

print(count)

2019/05/10 21:23

messi

a=range(1,10000)
check=0

for i in a:
    j=str(i)
    for k in range(len(j)):
        if int(j[k])==8:
            check+=1
        else:
            pass

print(check)

답 4000

2019/05/14 16:34

코딩동댕유치원

count=0
for i in range(1,10001):
    while i>0:
        if i%10==8:
            count+=1
        i=i//10

print(count)

파이썬-비쥬얼코드

2019/05/18 17:45

송민석

#1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?

#8의 개수
total = 0

for i in range(1,10000):
    number = str(i)
    find = number.count('8')
    total += find

print(total)

2019/05/19 17:09

jinoh

#include <iostream>

int count = 0;

void myGenerator(int a)
{

    int units = 0;
    int tens = 0;
    int hundreds = 0;
    int thousands = 0;

    if (a < 10) // 1~9
    {
        if (a == 8)
            count++;
    }
    else if (a < 100 && a > 9) // 10~99
    {
        units = a % 10;
        tens = a / 10;

        if (units == 8)
            count++;
        if (tens == 8)
            count++;

    }
    else if (a < 1000 && a > 99) // 100 ~ 999
    {
        hundreds = a / 100;

        tens = a / 10;
        tens = tens % 10;

        units = a % 10; 

        if (units == 8)
            count++;
        if (tens == 8)
            count++;
        if (hundreds == 8)
            count++;
    }
    else if (a <= 10000 && a > 999) // 1000 ~ 5000
    {
        thousands = a / 1000;
        //std::cout << thousands << std::endl;

        hundreds = a / 100;
        hundreds = hundreds % 10;
        //std::cout << hundreds << std::endl;

        tens = a / 10;
        tens = tens % 10;
        //std::cout << tens << std::endl;

        units = a % 10;
        //std::cout << units << std::endl;

        if (units == 8)
            count++;
        if (tens == 8)
            count++;
        if (hundreds == 8)
            count++;
        if (thousands == 8)
            count++;
    }
}


int main()
{
    for (int i = 0; i <= 10000; ++i)
        myGenerator(i);

    std::cout << count << std::endl;
}

2019/05/22 20:28

박인혁

include

int main() { int a=0, b=0, c=0, d=0; int count=0; for(;;) { d++; if(d==8) count++; if(c==8) count++; if(b==8) count++; if(a==8) count++; if(d==10) { c++; d=0; } if(c==10) { b++; c=0; } if(b==10) { a++; b=0; } if(a==10) break; printf("%d%d%d%d\n", a, b, c, d); } printf("%d", count); }

2019/05/27 10:23

홍정민

member=range(1,10000)
box=[]
for i in member:
    a=str(i)
    for ii in a:
        if ii=='8':
            box.append(ii)
print(len(box))

답은 4000 이군요... 짧게 가고싶은데..

2019/05/27 15:05

임희동

def run():
    cnt = 0
    for x in range(1, 10001):
        for s in str(x):
            if s == '8': cnt+=1
    print(cnt)

한 줄 안에 for 문을 두 개 넣을려고 하는 데 어떻게 해야할지 모르겠네요..

2019/05/27 15:26

이진형

for x in range(1, 10001): for s in str(x): if s == '8': cnt += 1 이런식으로 하면 됩니다 - CT_EK, 2019/06/13 09:17
class Solutions {
    int[] nums_array;
    int count = 0;
    Solutions() {
        nums_array = new int[10000];
        for(int i = 0; i < nums_array.length; i++) {
            nums_array[i] = i+1;
        }
    }
    int Check_for_8() {
        for(int i = 0; i < nums_array.length; i++) {
            int para = nums_array[i];
            while(para!=0) {
                if(para%10 == 8) {
                    count++;
                }
                para /= 10;
            }
        }
        return count;
    }

}
class Count_of_8 {
    public static void main(String[] args) {
        Solutions slt = new Solutions();
        System.out.print("결과: " + slt.Check_for_8());
    }
}

2019/05/29 11:27

우태균

8 _ _ 은 총 1000개, ( _ 은 000 부터 999 까지 있다.) _ 8 _ 도 1000개, 이런 꼴이 4개 니까 4 * 1000 = 4000. 정답은 4000개. - Made by GPS

2019/05/29 21:35

Firelight

public class Test1 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int cnt = 0;
        for(int i = 0 ; i < 10001; i++) {
            String k = Integer.toString(i);         
            for(int j = 0 ; j < k.length(); j++) {
                if(k.charAt(j) == '8') {
                    cnt++;
                }
            }
        }
        System.out.println("1부터 10000까지 8이 들어간 횟수 : "+ cnt);
    }
}

2019/06/04 15:22

신현준

count=0

for i in range(1,10001):
    if "8" in str(i):
        for coun in str(i):
            if coun =="8":
                count+=1
print(count)

2019/06/09 13:11

꽁잎

파이썬 3.7.2

nlist = [x for x in range(1, 10001)]
n = list(str(nlist)).count('8')
print(n)

답 : 4000

2019/06/13 09:15

CT_EK

import math

rs = 0;

for i in range(1,10001,1):
    o = math.trunc(i/10000)
    a = math.trunc(i/1000)  #ex i= 2645  a = 2
    b = math.trunc((i-(a*1000))/100)  #b = 6
    c = math.trunc((i-(a*1000)-(b*100))/10)
    d = (i-(a*1000)-(b*100)-(c*10))

    num = [o,a,b,c,d]

    for t in num:
        if(t == 8):
            rs= rs+1


print("8의 갯수",rs)


2019/06/22 14:26

나는인기쟁이

a=0
for i in range(10000):
  for x in str(i):
    if x=="8":
      a=a+1

2019/06/30 00:36

yo on

numList = str((list(range(1,10001))))

print(numList.count('8'))

2019/06/30 23:50

야어이구

count = 0 for i in range(1,10001): count += list(str(i)).count('8') print(count)

2019/07/01 14:02

SeongMin Hwang

count = 0 for i in range(1,10001): count += list(str(i)).count('8') print(count)

2019/07/01 14:02

SeongMin Hwang

a =''
for i in range(1,10001):
    a+=str(i)
print(a.count('8'))

2019/07/01 23:06

Hyebin Oh

tmp = 1
count = 0
while tmp <= 10000 :
    i = tmp
    i = list(str(i))
    for j in range(len(i)) :
        if i[j] == '8' :
            count += 1
    tmp += 1
print(count)

2019/07/02 00:06

조현우

N = 10001
counter = 0

for i in range(1, N):
    numStr = str(i)
    for j in range(len(numStr)):
        if numStr[j] == '8':
            counter += 1

print(counter)

python

2019/07/04 16:06

Wonsang Kim

a = list(range(1, 10001))    # 1~10001까지의 정수 리스트 a 생성
b = ''.join(map(str, a))     # 리스트 a의 요소들을 문자열로 바꾼 뒤 공백을 기준으로 join

print(b.count('8'))          # 8의 카운트값 출력

2019/07/06 15:25

종이

파이썬

man = list(range(1,10001))
eight = 0
for n in man:
    a = str(n).count('8')
    eight += a
print(eight)

2019/07/12 00:35

사닐

def solution(n):
    c = 0
    for i in range(1,n+1):
        i = str(i)
        for j in range(len(i)):
            if i[j] == '8':
                c += 1
    return c

print(solution(10000))

2019/07/12 10:30

최은미

{.python} sum=0 for i in range(1,10001): for n in (list(str(i))): if n=="8": sum+=1 print(sum)

2019/07/14 14:45

서광석

public class Number {

    public static void main(String[] args) {
        int count = 0;

        for(int i=1; i<=10000; i++) {
            String str = null;
            str = "" + i;
            for(int j=0; j<str.length(); j++) {
                if(str.charAt(j) == '8') {
                    count++;
                }
            }
        }
        System.out.println("8의 총수량은 : " + count);

    }

}

답은 4000 나옵니다

2019/07/22 19:05

김남일

public class eightCount {

    public static void main(String[] args) {
        int start=1, range=10000, count=0;
        for (int i = start; i<(start+range); i++) {
            String str = Integer.toString(i);
            for(int j = 0; j < str.length(); j++) {
                if((str.charAt(j)-'0')==8) {
                    count++;
                }
            }
        }
        System.out.print(start + "과 " + (start+range-1) +"까지 8의 갯수는 " + count + "개 입니다.");
    }
}

2019/07/22 22:43

김준성

python 3.7

str(list(range(1,10001))).count("8")

2019/07/24 10:47

AY

x=[str(i) for i in range(1,10000)]
q=0
for i in x:
    if '8' in x:
        q+=i.count('8')
print(q)
``````{.python}
print(str(list(range(1,10001))).count('8'))

2019/07/24 12:44

유선종

def multiples(num):
    cnt = 0
    for i in range(num):
        for j in str(i):
            if int(j) == 8:
                cnt += 1
    return cnt

print(multiples(10000))

2019/07/25 13:18

py_code

print(sum(list((str(i).count("8") for i in range(10001)))))

2019/07/25 20:45

최혁제

def count():

    string=""
    for i in range(1, 10001):
        string += str(i)
    return(string)


string=count()

c8=string.count("8")

print(c8)

2019/07/31 14:09

Hwain Choi

많이 배우고 갑니다! 분발하겠습니다!

저는 C를 이용했습니다!

#include <Stdio.h>
/*1~10000까지 8이 몇 개가 있을지
나의 생각:숫자가 들어오면 그 숫자를 각 자릿수로 쪼갠다
*/
#define LIMIT_MAX 10000

int jari(int value)
{
    int jari = 0;
    while (value != 0)
    {
        jari++;
        value = value / 10;
    }

    return jari;
}
int main()
{
    int space[5] = { NULL };
    int count = 0;
    int value = 0;
    int digit = 0;
    for (int i = 0; i < LIMIT_MAX; i++)
    {
        digit = jari(i + 1);

        value = i + 1;

        int index = 0;
        while (value > 0)
        {
            space[index] = value % 10;
            index++;
            value = value / 10;
        }

        for (int j = 0; j < digit; j++)
        {

            //자릿수 크기의 배열에서 생각           

            if (space[j] == 8)
            {
                count++;
            }
        }

    }

    printf("1에서 10000까지 8의 개수는 %d개 입니다\n", count);


}

2019/08/03 15:42

정지수

count8: int = 0
for num in range(1, 10001):
    for a in str(num):
        if '8' == a:
            count8 += 1
print(count8)

2019/08/05 23:49

불나방

def prob(num): # 1부터 n까지의 입력을 받음, 또한, n값은 1000, 100000 같은 형태로 받음
    n=len(str(num))
    cnt = n-1 # 모든 자리의 수가 8인 경우를 설정.
    for i in range(1,(n-1)):
        cnt += 9**(n-1-i)*comb(n-1,i)*i
    print(cnt)
def fac(num):
    if num==1:
        return 1
    return num*fac(num-1)
def comb(num1,num2):   # (num1) C (num2)
    return fac(num1)/(fac(num2)*fac(num1-num2))

2019/08/07 10:52

최재학

eight = 0
for x in range(1,10001) :
    for i in str(x) :
        if i == '8' :
            count = count +1
print(eight, " times")

2019/08/08 20:15

Minseok Choi

cnt=0
for i in range(1,10000):
    a=str(i)
    n=len(a)
    for j in range(0,n):
        if '8' in a[j]:
            cnt+=1
print(cnt)

2019/08/09 12:52

이성표

python

count = 0
for i in range(1,10001):
    if '8' in str(i):
        count += list(str(i)).count('8')
count   

2019/08/10 22:25

apriori

num=0
for i in range(1,10001,1):
    num=num+str(i).count('8')

print(num)

2019/08/14 15:07

박재욱

c=0
for i in range (1, 10001):
    for j in str(i):
        if j=='8':
            c+=1
print(c)

2019/08/18 10:57

J K

i=0
for e in range(1, 10001):
    for n in str(e):
        if n == '8': i+=1
print(i)

2019/08/22 17:02

돔돔

from random import *
sum = 0
for i in range(1,10001):
    k = str(i)
    count = k.count('8')
    sum +=count
print(sum)

2019/08/27 15:28

김상호

count=1
for a in range(0,10000):
    for b in list(str(a)):
        if '8' in b:
            count+=1
print(count)

2019/08/28 17:20

Cosu

eit=0
for i in range(1,10001):
    for j in str(i):
        if int(j)==8:
            eit+=1

print(eit)

2019/09/04 00:31

정민석

count = 0 for i in range(1,10000): for j in str(i): if "8" in j: count += 1 print(count)

2019/09/09 13:36

김민규

package sec01.exam01;

public class HelloJava {

    public static void main(String[] args) {
        int i, temp, count = 0;

        for (i = 1; i <= 10000; i++)
        {
            temp = i;
            while (i > 0)
            {
                if (i % 10 == 8)
                    count++;
                i /= 10;
            }
            i = temp;
        }

        System.out.println("1부터 10000까지 수에서 8의 개수 = " + count + "\n");
    }
}

temp를 안 넣고 하니 컴파일 할 때 프리징이 오네요... 아마 for 문 내에서 while 문 실행 시 i가 바뀌었고, 그 바뀐 i 값 때문에 반복문이 작동하지 않는다 생각해 temp로 기존 i값을 보존하는 방법을 사용하긴 했습니다. 제가 생각한 원인이 맞나요? 기존 코드는 temp = i; , i = temp; 를 넣지 않았습니다.

2019/09/10 17:07

OverEasy

PHP

$result = substr_count(implode(range(1, 10000)), 8);

print_r($result); // 4000

2019/09/10 17:44

d124412

print(str(list(range(1, 10001))).count('8'))

2019/09/18 12:54

Woonghee Lee

print(sum([str(a).count("8") for a in range(0,10000)]))

2019/09/22 01:20

ikc

"".join([str(i) for i in list(range(1, 10001))]).count("8")

결과

4000

2019/09/27 11:38

GG

int cnt = 0;

        for(int i=1; i<10000; i++) {
            char[] num = Integer.toString(i).toCharArray();
            for(char ch : num) {
                String str = String.valueOf(ch);
                if("8".equals(str)) cnt++;
            }
        }
        System.out.println(cnt);

1부터 10000까지 숫자를 toString.toCharArr()로 바꾼 후 i<toCharArr.length까지 arr[i]에 대해== "8"이면 cnt++ 답 : 4000

2019/09/30 20:33

yeeun shim

sum = 0
for i in range(10001):
    a = str(i).count('8'); sum += a
print(sum)

2019/10/03 14:46

이명운

C#

count = 0;

for (int i = 1; i <= 10000; i++)
    for (int j = i; j > 0; j /= 10)
        count += j % 10 == 8 ? 1 : 0;

Console.WriteLine(count);

2019/10/05 06:19

씨샵 짱짱맨

print(str([i for i in range(1,10001)]).count('8'))

2019/10/06 16:00

후눈

anw=0
for i in range(1,10001):
    if i%10000-i%1000==8000:
        anw+=1
    if i%1000-i%100==800:
        anw+=1
    if i%100-i%10==80:
        anw+=1
    if i%10==8:
        anw+=1

print(anw)

2019/10/07 16:03

재철심

C# Interactive

string.Concat(Enumerable.Range(1,10000)).Count(c=>c=='8')

2019/10/08 04:19

씨샵 짱짱맨

class Solution(object):
    def count_8(self, num):
        cnt = 0
        while num > 0:
            num, rem = divmod(num, 10)
            if rem is 8:
                cnt += 1
        return cnt

if __name__ == "__main__":
    sol = Solution()
    cnt = 0
    for val in range(1, 10001):
        cnt += sol.count_8(val)
    print cnt

2019/10/10 07:42

RumbleBang

Best Practice 참조

str(list(range(1, 10001))).count('8')

2019/10/17 16:19

Koh KT

temp = 0
for i in range(1,10001):
    comp_str= str(i)
    for ch in range(len(comp_str)):
        if '8' == comp_str[ch]:
            temp += 1
print(temp)

2019/10/19 00:25

semipooh

number=int(input())
print((str(list(range(1,number+1)))).count('8'))

2019/11/11 14:05

Red brick


public class Number8 {

    static int counter=0;

    public void chk(int chker) {

        if(chker==8) {counter++;
        }       
    }

    public static void main(String[] args) {

        Number8 number = new Number8();

    for(int i=1; i<=10000; i++) {
        int a,b,c,d;

        a=i/1000%10;
        b=i/100%10;
        c=i/10%10;
        d=i%10;

        number.chk(a);
        number.chk(b);
        number.chk(c);
        number.chk(d);
        }   

    System.out.println(counter);
}}

2019/11/12 13:52

Arisia T

import java.util.*;
public class 구글입사문제중에서 {

    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<Integer>();
        String[] list = new String[10001];
        for(int s = 0; s<list.length; s++) {
            list[s] = String.valueOf(s);
        }

        for(int k=0; k<list.length; k++) {
            String[] num = list[k].split("");
            int count = 0;
            for(int l=0; l<num.length; l++) {
                if(num[l].equals("8")) {
                    count++;
                }
            }
            nums.add(count);
            num = null;
        }
        int sum=0;
        for(int a=0; a<nums.size(); a++) {
            sum+=nums.get(a);
        }
        System.out.println(sum);
    }
}
//제가 너무 어렵게 푼 것 같네요...
//다른분들 대단하네요..

2019/11/15 15:39

big Ko

파이썬 3.6 입니다

def count_eight(n):
    number_pool = (n for n in range(1, n + 1))
    counter = 0

    for i in number_pool:
        counter += [c for c in str(i)].count('8')
    return counter

print(count_eight(10000))

2019/11/21 19:43

vkospi

print sum([[int(i) for i in str(x)].count(8) for x in range(1,10000)])

파이썬으로 풀어봣어요

2019/11/26 10:49

오오옹

def count8(n):
    result = 0
    for i in str(n):
        if i == '8':
            result += 1
    return result

A = [count8(i) for i in range(1,10001)]
print(sum(A))

정수 n 내에 존재하는 8의 갯수를 찾는 함수를 만들고, 1부터 10000까지 숫자에 대해 함수를 실행하여 합을 구함

B = ''
for i in range(1,10001):
    B += str(i)

sum_ = 0
for i in B:
    if i == '8':
        sum_ += 1

print(sum_)

1부터 10000까지 문자열로 붙여 쓴 다음, 문자열 인덱싱을 통해 8을 찾을때마다 sum을 1씩 더해서 최종 값을 출력

2019/12/18 05:16

D.W. Choi

파이썬 내장함수인 count를 이용하면 어렵진 않은거 같애요.

i=0
count=0
for i in range(10000):
    count=count+str(i).count('8')

2019/12/19 00:53

김동석

굳이 사용해본 반복문 in 파이썬3

result = 0
for i in range(1, 10001):
  for j in str(i):
    if j == '8':
      result += 1
print(result)

2019/12/21 12:13

Sean

l=[]
for n in range(1,10001):
    n=str(n)
    if "8" in n:
        l.append(n)
ec=0
for k in l:
    en=k.count("8")
    ec+=en
print(ec) #4000

# 또는 아래와 같이 한줄로 간단하게
print(str(list(range(1,10001))).count("8"))

2019/12/25 16:28

박시원

파이썬

number=[str(i) for i in range(1,10001)]
count=0
for j in number:
    for k in j:
        if int(k) == 8:
            count += 1
print(count)
# 4000

2019/12/27 17:34

data big

print(str(list(range(1,10001))).count('8'))

2019/12/28 17:14

뚜루꾸까까

Javascript(ES6)...

`1 부터 10,000 까지의 숫자를 하나의 긴 문자열로 생성, 그 문자열에서 '8' 숫자만을 정규식으로 추출하여 추출된 배열 길이 측정`;

let result;
result = [...Array(10001).keys()].slice(1);      // 1 ~ 10,000 까지 숫자가 채워진 배열 생성
result = result.join('');                        // 배열안에 있는 숫자를 이어붙여 하나의 문자열로 생성
result = result.match(/8/g).length;              // 문자열에서 8 만 추출하여 배열을 생성, 그 길이를 잼

console.log(result);    // 4000

Python 3...

print(''.join([str(i) for i in range(1,10001)]).count('8'))

2019/12/31 17:25

tedware

#include<stdio.h>

int main(){
    int i, sum=0;
    for(i=1;i<=10000;i++){
        int a=i/1000;
        int b=(i-a*1000)/100;
        int c=(i-a*1000-b*100)/10;
        int d=i%10;
        if(a==8) sum++;
        if(b==8) sum++;
        if(c==8) sum++;
        if(d==8) sum++;
    }
    printf("%d",sum);
}

2020/01/04 15:24

곽병혁

package codingdozang;

public class Count8 {
    public static void main(String[] args) {
        int i, sum=0;
        for(i=1;i<=10000;i++) {
            int a=i/1000;
            int b=(i%1000)/100;
            int c=(i%100)/10;
            int d=i%10;

            if(a==8) sum++;
            if(b==8) sum++;
            if(c==8) sum++;
            if(d==8) sum++;
        }
        System.out.println(sum);
    }
}

2020/01/04 15:30

곽병혁

finCnt = 0
numList = list(map(str,range(1,10001)))
tmp = []
for i in numList:
    for j in i:
        if j == '8':
            finCnt += 1

print(finCnt)

2020/01/14 22:29

Jung Marco

N = 10000
count = 0

for i in range(N + 1):
    for j in range(len(str(i))):
        count += (str(i)[j] == '8')

print('1부터 {0}까지 8이라는 숫자는 {1}번 나온다'.format(N, count))

2020/01/16 20:48

우재용

class CT { int counter = 0;

int count(int i) {
    if(i / 1000 == 8)   {   ++counter;  }
    if((i % 1000) / 100 == 8)   {   ++counter;  }
    if((i % 100) / 10 == 8) {   ++counter;  }
    if(i % 10 == 8) {   ++counter;  }
    return counter;
}

}

public class 구글_8개수세기 { public static void main(String[] args) { CT c = new CT();

    int total = 0;

    for(int i = 1; i <= 10000; i++)
    {
        c.counter = 0;
        total += c.count(i);
    }
    System.out.printf("1 ~ 10000까지 8의 개수는 %d개이다.", total);
}

} 정답은 4000입니다. ( JAVA )

2020/02/03 23:39

하루

public class FindNumber {
    public static void main(String[] args) {
        int count =0;
        for(int i = 1; i<=10000; i++) {         //1부터 10000까지 8이나오는 횟수 찾기
            if(i%10 == 8) {                     //1의 자리
                count++;
            }
            if(((i/10)%10)==8) {                //10의 자리
                count++;
            }
            if(((i/100)%10)==8) {               //100의 자리
                count++;
            }
            if(((i/1000)%10)==8) {              //1000의 자리
                count++;
            }
            if(i==10000) {
                break;
            }
        }
        System.out.println("정답: "+ count);
    }
}

2020/02/04 22:08

김강민

c = 0

for x in range(1, 10000):

a = [int(a) for a in str(x)]

b =(int(a.count(8)))

c = b+c

print(c) ```

2020/02/13 14:50

HyukHoon Kim

print(sum([str(i).count('8') for i in range(1,10001)]))

2020/02/14 11:34

BlakeLee

a = []

for b in range(1,10001):

    a.append(b)

print(a.count(8))

c = list(map(str,a))

d = "".join(c)

print(d.count('8'))

2020/02/14 15:07

Junghan Shin

result = 0
for i in range(1,10000):
    str_i = str(i)
    len_i = len(str_i)
    for j in range(len_i):
        if '8' in str_i[j]:
            result +=1
print(result)

2020/02/16 19:10

카레맛카레

eight = 0

for i in range(1, 10000):
        num = list(str(i))
        for j in range(0, len(num))
                num[j] = int(num[j])
                if 8 in num:
                        eight += 1
                j += 1


2020/02/17 00:13

PythonLover&Master_JK73

파이썬 3.8.1 입니다.

#-*- coding:utf-8 -*-

result = [] # 결과 도출용 리스트
for x in range(1,10000):
    result.extend([int(n) for n in str(x)]) # 각 자리 숫자를 뽑아 리스트 삽입

print(result.count(8)) # 8의 갯수

2020/02/19 00:43

Sanghyuk Woo

a = list(i for i in range(1,10001))
sum = 0
for i in range(len(a)):
    a[i] = str(a[i])
    if a[i].count('8') != 0:
        sum += int(a[i].count('8'))

print(sum)

2020/03/01 21:32

유맹

from pandas import Series, DataFrame
a=Series(range(1,10001)).astype(str)
def count_8(x):
    return(x.count('8'))

a.apply(count_8).sum()

2020/03/05 18:25

taehun kim

cnt=0
for i in range(10001):
    if i%10==8 :
        cnt=cnt+1
    elif (i%100)//10 ==8:
        cnt =cnt+1
    elif (i%1000)//100 ==8:
        cnt=cnt+1
    elif i//1000 ==8:
        cnt=cnt+1
print(cnt)

2020/03/06 14:07

sotmef222

python

count=0
for i in range(0,10001):
    str_i = str(i)
    for n in range(0,len(str_i)):
        if str_i[n-1]=='8':
            count += 1
print(count)

2020/03/06 17:09

Junghoon Kim

i_tmp = ((','.join(str(list(range(1,10001)))))[1:-1].split(',')).count('8')

2020/03/07 11:50

Yanghee Lee

lst=[]
cnt=0
for i in range(1,10001):
    for j in str(i):
        lst.append(j)

print(lst.count('8'))

2020/03/08 22:52

황예진

sum([1 for i in range(1, 10000) for j in list(str(i)) if j=='3'])

if 문으로 걸러진 3을 전부 더하는 방식입니다.

2020/03/09 14:49

_김준희_

count = 0
for i in range (1, 10000+1):
    count += str(i).count('8')

print(count)

2020/03/19 00:54

뤼크

#include<iostream>
#include<string>
using namespace std;
/*
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?

8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
*/


//정답: 4000
void Func(int n) {
    int count = 0;
    int c;
    bool check;
    for (int i = 1; i <= n; i++) {
        string s = to_string(i);
        c = 0;
        check = false;
        for (int j = 0; j < s.length(); j++) {
            if (s[j] == '8') { ++count; ++c; check = true; }
        }
        if (check) { cout << s << " = " << "8개수:" << c << endl; }
    }
    cout << "1부터" << n<<"까지 8의 총 개수는=" << count << endl;
}

int main() {
    Func(10000);
}

2020/03/20 16:57

++C

a = range(1, 10000)
b = str(list(a))
howmany = 0

for i in b:
    if '8' in i:
        howmany += 1

print(howmany)

2020/03/21 09:07

최형석

python list comprehension 활용했습니다.

print(sum([str(x).count('8') for x in range(1,10000+1)]))

2020/03/22 09:17

jjojjo

n=0
for i in range(1,10001):
    for k in str(i):
        if k=='8':
            n+=1
        else:
            pass
print(n)

2020/03/28 21:41

di figo

def count_8(n): global sum

if (n==8):
    sum+=1
return sum

def divid(m): global sum

str_m=str(m)
len_m=len(str_m)

for i in range(len_m):
    count_8(int(str_m[i]))

print('8의 갯수는:',sum)

sum=0 divid(88558)

2020/03/31 01:50

김가영

answer = sum([str(x).count('8') for x in range(1, 10001) if str(x).count('8') >= 1 ])

2020/04/01 19:58

candy GP

count = 0
for i in range(1, 10001):
    t_str = str(i)
    for j in range(len(t_str)):
        if t_str[j:j+1] == '8':
            count += 1
print('1~10000범위에 8이 들어간 횟수는 {}번 입니다'.format(count))

저도 언젠가는 다른 분들 처럼 언어를 잘 알아서 알고리즘을 세워 한줄로 코딩하는 날이 오겠죠..

2020/04/01 23:48

잘해보자

_sum = 0
a = 0
for i in range(1,10001):
    a = str(i)
    if a.count('8') >= 1:
        _sum += a.count('8')
print(_sum)

파이썬 / 한줄짜리 코드가 정말 많네요.

2020/04/02 11:36

기둘비

            char Number[5] = {0, };
            int nCount = 0;

            for(int c = 1 ; c <= 10000 ; c++)
            {
                itoa(c, Number, 10);

                for(int i = 0 ; i < strlen(Number) ; i++)
                {
                    if(Number[i] == '8')
                    {
                        nCount++;
                    }
                }
            }

2020/04/08 21:47

길고양이

num = 0

for i in range(10001):
    for j in str(i):
        if j == '8':
            num += 1

print(num)

2020/04/15 21:00

ptjddn95

파이썬이라 단순하게 작성할 수 있었어요

a=list(range(10001))
number=str(a)
print(number.count('8'))

2020/04/19 22:15

Dongsuk Kim

sum = 0

for x in range(10001):
    for i in str(x):
        if i == "8" :
            sum += 1
print(sum)

2020/04/22 22:57

최민기

count=0
for i in range(1,10001):
    chr=str(i)
    for i in range(len(chr)):
        if chr[i]=="8":
            count+=1
print(count)

2020/04/23 21:57

kim center

count = 0
for n in range(1,10001):
    count += str(n).count("8")
print(count)

2020/04/24 14:36

YB Jung

sum=0
for i in range(10000):
    a=str(i)
    b=a.count('8')
    sum+=b
print(sum)

2020/04/25 00:15

양양짹짹

b = 0
for i in range(1,10001):
    ilis =str(i)
    for a in ilis[:]:
        if a == '8':
            b = b + 1
print(b)

2020/04/25 01:31

B and V Before

파이썬

sum=0 for i in range(10001): a=str(i).count('8') sum += a print(sum)

2020/05/03 09:48

kim ih

파이썬입니다.

num = []
counting = []
for x in range(1,10001):
    num.append(x)
for x in num:
    for i in str(x):
        if int(i) == 8:
            counting.append(i)

print(len(counting))

2020/05/07 18:28

peca lee

print(str(list(range(1,10001))).count('8'))

예를들어 a = "18"의 경우 a.count('8')을 하면 1을 출력하네요^^ 배워갑니다~

2020/05/10 18:59

Money_Coding

def iterate8s(lower, upper):
    result = 0
    for i in range(lower, upper+1):
        while i:
            if i % 10 == 8:
                result += 1
                i /= 10
                i = int(i)
            else:
                i /= 10
                i = int(i)

    return result

생각 없이 풀었습니다.

2020/05/13 01:02

길광연

function getNumber(num) {
    num = num.toString();
    var index = 0;
    var count = 0;
    while(num[index]) { 
        if(num[index].match("8")) { count++;}
        index++; 
    };
    return count;
  }

var countResult = 0;
for(var index = 0; index < 10000; index++){
    countResult += getNumber(index);
}

console.log(countResult);

2020/05/22 13:56

김저승

count = 0
for i in range(10000):
    for j in range(len(str(i))):
        if str(i)[-j] == '8':
            count += 1
print(count)

2020/05/27 08:49

aryagaon

def cal(num):
    global count
    for m in range(1,len(str(num))):
        ma=num%10
        num=num//10
        if ma==8:
            count+=1
        if num==8:
            count+=1

count=0

for i in range(1,10001):
    cal(i)

print("결과 : ", count,"회")

파이썬 왕초보입니다. 위와 같은 방법으로 구하면 결과가 3999회가 나오는데 무엇이 잘못된 것인가요? 아무리 생각해봐도 제 능력으로 구현할 수 있는 logic은 이것밖에 없었습니다.

2020/05/27 15:15

sjmw

numbers = []

for num in range(10001):
    for i in str(num):
        if '8' in i:
            numbers.append('8')

            print(numbers.count('8'))

#매핑으로 str->int 로 바꿔서 더하려고했으나 count함수로 그냥 리스트에있는 스트링을 더했습니다
#a = map(int, numbers) 

#파이썬 코딩 공부 제대로 한지 4일차인 코린이입니다..
#드디어 처음으로 문제 풀었네요 코드도 길고 장황하지만ㅠ 기뻐서올립니다

2020/05/28 11:27

이해빈

print(''.join(map(str,range(1,10001))).count('8'))

2020/06/04 15:38

space

c = []   

for i in range(1,10001):
    for a in str(i):
        b = int(a)
        c.append(b)

print(f"{c.count(8)}")

정답은 4,000개 맞나요?!

2020/06/07 12:56

Taek Kor_

count = 0
for i in range(10001):
    for j in list(str(i)):
        if j == '8':
            count += 1
print(count)

2020/06/07 16:30

zeusrornfl

파이썬3입니다.

n = 10000

print(str(list(range(1, n+1))).count('8'))

2020/06/17 09:58

누마루

result = 0

for i in range(1,10001):
    result += str(i).count('8')

print(result)

2020/07/01 16:29

안성빈

count8 = 0

for i in range (1,10001):
    if i//1000 == 8 :
        count8 += 1
    if (i-(i//1000)*1000)//100 == 8 :
        count8 += 1
    if (i-(i//100)*100)//10 == 8 :
        count8 += 1
    if (i-(i//10)*10) == 8 :
        count8 += 1

답은 4000

2020/07/10 18:17

ARIADNE


import java.util.Scanner;

public class main {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.print("찾고 싶은거 뭐임:");
        int find = scan.nextInt();

        for(int i=1;i<=10000;i++)
        {
            search(find,i);
        }

        System.out.println("총 갯수: " + result);
    }

    private static int result=0;
    public static void search(int find,int num) {
        if(num%10 == find)
            result++;
        if(num>10)
            search(find,num/10);
    }

}

2020/07/14 14:29

허병우

a=0
for i in range(1,10001):
    for j in str(i):
        if j == '8':
            a+=1
a

2020/07/17 17:21

hand coder

count = 0
for i in range(1, 10001):
    for s in str(i):
        if s == '8':
            count += 1
print(count)

2020/07/23 07:35

Chang-Hoon Lee

arr = list(range(1,10000))
Countarr = str(arr).count('8')
print(Countarr)

2020/07/23 16:33

JaeWon Lee

print(sum([str(i).count('8') for i in range(1,10001)]))

2020/07/26 05:44

김병관

파이썬 입니다.

count=0
for i in range(1,10001):
    b=str(i)
    a =  list(b)
    if '8' in a:
        for i in a:
            if i=='8':
                count+=1
            else:
                pass
    else:
        pass
print(count)

2020/08/16 16:38

wanna be programmer

package test;
import java.util.*;

public class Test{
    public static void main(String[] args) {
        int i = 1;
        int count = 0;
        ArrayList<String> arr = new ArrayList<>();
        while(i<=10000) {
            arr.add(Integer.toString(i));
            i++;
        }
        for(String e : arr) {
            for(int j = 0; j<e.length(); j++) {
                if(e.charAt(j) == 56)
                    count++;
            }
        }
        System.out.print(count);
    }
}

2020/08/19 14:57

들산

파이썬으로 작성하였습니다.

eight_counts = 0
for num in range(1,10001):
    for x in str(num):
        if int(x) == 8:
            eight_counts += 1
print(eight_counts)

2020/08/20 16:13

코딩수련수련자

cnt = 0
for i in range(10000):
    for item in str(i):
        if item=='8':
            cnt += 1
print(cnt)

2020/08/25 15:18

Bbb Aaa

package example01;

public class Google2 {

    public static void main(String[] args) {

        int count=0;
        //무식하게 해봣습니다
        for(int a=0;a<10;a++) {
            for(int b=0;b<10;b++) {
                for(int c=0;c<10;c++) {
                    for(int d=0;d<10;d++) {
                    if(a==0) {
                        count++;
                    }
                    if(b==0) {
                        count++;
                    }
                    if(c==0) {
                        count++;
                    }
                    if(d==0) {
                        count++;
                    }
                    }
                }
            }
        }

        System.out.println(count);
    }
}

2020/09/02 15:50

뚜떱 sooyeon_surf

print(str(list(range(10000))).count('8'))

하지만 말씀대로 코딩 문제는 아닌 듯 합니다...

2020/09/10 21:22

Typie

public class test4 {
    public static void main(String[] args) {
        String hatena = "";
        int answer = 0;
        for(int a = 0; a < 10000; a++) {
            hatena += String.valueOf(a);
        }
        for(int i = 0; i < hatena.length(); i++) {
            if(hatena.charAt(i) == '8') {
                answer++;
            }
        }
        System.out.println("정답 : "+ answer);
    }
}

구글이 원한 답은 아니겠죠? ㅋㅋㅋ

2020/09/11 18:30

nazunamoe

num8=0
for x in range(1,10000):
    x=str(x)
    num8+=x.count('8')
print(num8)

2020/09/22 17:01

안녕하세요

cnt = 0

for x in range(1,10001):
    for y in str(x):
        if y == '8':
            cnt += 1
print(cnt)

2020/09/29 09:50

이셩

#먼저 숫자 범위를 입력 받음.(a=1,b=10000)
#숫자 범위 만큼 for문을 돌린다.
#8728이들어왔다고 치면
#i라는 숫자를 문자로 변환 시켜준다. str() 함수는 정수를 문자열로 반환해줌.
#그러면 8728이라는 숫자는 check ['8','7','2','8']과 같음
#이제 list의 내장 함수인 count를 이용함.
#count('1')이 오면 리스트 안에 '1'라는 문자가 몇개 있는지 확인함.
#따라서 check.count('8')을 하면 check 안에 있는'8'이라는 문자의 갯수를 확인하고 반환해줌.
#그 숫자를 number을 통해서 덧셈을 계속 해주면 됨.


def solve(a,b):
    number = 0
    c = []
    for i in range(a,b+1):
        check = str(i)
        #---------없어도 되는 부분----------
        if '8' in check:
            c.append(i) #이건 그냥 밑에 있는 8들어간 숫자 보여줄려고 있는 코드임.
        #-----------------------------------    
        number += check.count('8')
    print("count = %d"%number)

    #8이 들어간 숫자들을 볼려면 주석을 해제하면 됨
    """
    count = 1
    for i in c:
        print(str(count),i)
        count+=1
    """    

2020/10/01 22:35

jaewook Lee

#include<stdio.h>

int main()
{
    int i,j,c=0;

    for(i=1;i<=10000;i++)
    {
        for(j=1;j<=10000;j*=10)
        {
            if((i/j)%10==8)
                c++;
        }
    }

    printf("%d",c);
    return 0;
}

j 부분이 포인트

2020/10/01 23:31

June

using System;
using System.Text.RegularExpressions;

namespace _62일차_10월02일
{        
    class MainApp
    {
        static void Main(string[] args)
        {
            string Data = "";
            for (int i =1; i < 10000; i++)
            {
                Data += i.ToString();
            }

            MatchCollection matches = Regex.Matches(Data, "8");
            int cnt = matches.Count;
            Console.WriteLine($"Result = {cnt}개");
        }
    }
}

2020/10/02 14:25

MinSeung Kang

public static int countNum(int target, int number) {        
        int count = 0;
        for (int i = 1; i < target+1; i++) {
            int n = i;
            if(n<10) {
                if(n%10==number) count++;
            }else if(n>9) {
                while(n>0) {
                    if(n%10==number) count++;
                    n = n/10;                   
                }
            }
        }
        return count;
    }

2020/10/05 16:53

B A

자바입니다.```{.java} public class google {

public static void main(String[] args) {
    int count = 0;
    for(int i=1;i<=10000;i++) {
        int a=i;
        while(a/10>=0) {
            if(a%10==8) {
                count++;
            }
            if(a/10<1) {
                break;
            }
            a/=10;
        }
    }
    System.out.println(count);
}

} ```

2020/10/15 11:57

ᆞᄉ

num = []

for i in range(10000):
    i = str(i)
    num.append(i)

num_2 = "".join(num)
num_2


num_2.count('8')

2020/10/17 11:34

계진석

ans = 0
for i in range(10000) :
    ans = ans + str(i).count("8")
print ans

2020/10/17 23:51

Centro

4000개 xxx8,xx8x,x8xx,8xxx이므로 1000+1000+1000+1000

2020/11/03 20:25

고태욱

li1 = []
for x in range(1,10001):
    x = str(x)
    if x.count('8')!=0:
        y = x.count('8')
        li1.append(y)
    else:
        pass

print(sum(li1))

python 3.9.0

2020/11/05 03:42

김태관

package codeDojang;

import java.util.Scanner;

public class Prac {
    public static void main(String[] args) {

        int cnt=0;

        for(int i=1;i<=10000;i++) {
            int tmp = i;
            while(tmp/10!=0) {
                if(tmp%10==8) {
                    cnt++;
                }
                tmp/=10;
            }//end while
            if(tmp%10==8) cnt++;
        }
        System.out.println(cnt);
    }
}

2020/11/16 23:13

yijun kim

print(sum([str(i).count('8') for i in range(1,10001)]))

2020/11/23 16:07

김우석

cnt = 0

for i in range(1,10000):
    for j in str(i):
        if j == '8':
            cnt += 1

print(cnt)

2020/11/27 09:57

안상원

def counter8(text):
    count = 0
    for i in range(1,text):
        for aa in list(str(i)):
            if aa == '8':
                count += 1
    return count

print(counter8(10000))

2020/11/30 08:37

DSHIN

package main;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int cnt = 0;
        String[] str = new String[10000];
        for (int i = 0; i < str.length; i++) {
            str[i] = " "+ i;
        }
        for (int i = 0; i < str.length; i++) {
            for (int j = 0; j < str[i].length(); j++) {
                if(str[i].charAt(j)=='8') {
                    cnt+=1;
                }
            }
            System.out.println(str[i]+" "+cnt);
            cnt = 0;
        }
    }
}

2020/12/08 23:49

김준혁

count=0

for i in range(1,10001,1):

  number=str(i)

  for i in number:

    if "8"==i:

      count+=1

print(count)

2020/12/11 16:24

전준혁

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int count=0;
    int i=10000;
    int a=0;
    int _a;
    while(i--) {
        _a=a;
        while (_a!=0) {
            if(_a%10==8) {
                count++;
            }
            _a=_a/10;
        }
        cout << i << endl;
        a++;
    }   
    cout << count << endl;
    return 0;
}

2020/12/11 23:36

배민준


public class Numberof8 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //1부터 10000까지 8의 개수
        int a=0, b=0, c=0, d=0;
        int num=0;
        for(int i=0; i<10000; i++) {
            a=i%10;
            b=i/10%10;
            c=i/100%10;
            d=i/1000;
            if(a==8) num++;
            if(b==8) num++;
            if(c==8) num++;
            if(d==8) num++;
        }
        System.out.println("1부터 10000까지 8의 개수는 : "+num);
    }

}

2020/12/14 21:29

이정섭

#include <iostream>
#include <string>

using namespace std;

int main() {
    ios::sync_with_stdio();
    int countdata = 0;
    for (int i = 1; i <= 10000; ++i) {
        string data = to_string(i);
        for (int i = 0; i < data.length(); ++i) {
            if (data[i] == '8') {
                countdata++;
            }
        }
    }
    cout << countdata << endl;
}

2020/12/18 09:13

BlakeLee

a = []
for i in range(1, 10001):
    a += list(str(i))

print(a.count("8"))

파이썬으로 작성했습니다.

1부터 10,000까지의 자연수를 분리하여 리스트에 넣고, 해당 리스트에서 8을 세어 출력했습니다.

정답은 4000 입니다.

2020/12/19 23:38

임준혁

def fac(num):
    mul = 1
    for i in range(1,num + 1):
        mul *= i
    return mul    
def fcombination(num):
    a = 1
    for i in range(0, num):
        a *= (4 - i)
    f = fac(num)
    return a / f

s = 0    
for count in range(1,4):
    result = fcombination(count)
    result = result * 9**(4-count) * count
    s += result
print((s + 4))    

학실히 경우의 수로 푸니까 루프 별로 안돌아서 좋네요

2020/12/27 13:53

guma go

sum([True for x in range(1,10001) for a in str(x) if a =='8'])

2020/12/27 21:48

hankyu

JavaScript

let arr = Array.from({length: 10000}, (v , i) => i + 1);
let count = arr.join('').match(/8/g).length;
console.log(count);  // 4000

정답 : 4000

2020/12/28 13:18

DAMON

count = 0
for i in range(10000):
    if i >= 1000 and i < 10000:
        a = i//1000
        b = (i%1000)//100
        c = (i%100)//10
        d = (i%10)//1
        if a == 8:
            count += 1
        if b == 8:
            count += 1
        if c == 8:
            count += 1
        if d == 8:
            count += 1

    elif i >= 100 and i < 1000:
        b = i // 100
        c = (i % 100) // 10
        d = (i % 10) // 1
        if b == 8:
            count += 1
        if c == 8:
            count += 1
        if d == 8:
            count += 1
    elif i >= 10 and i < 100:
        c = i // 10
        d = (i % 10) // 1
        if c == 8:
            count += 1
        if d == 8:
            count += 1
    elif i >= 1 and i < 10:
        d = i
        if d == 8:
            count += 1

print(f'1부터 10000까지의 숫자중에 8이 나오는 횟수는 {count}')

2020/12/29 21:07

Mount

Python입니다.

a = 0
>>> for i in range(1, 10000):
...     b = list(str(i))
...     a += b.count('8')
...
>>> print(a)
4000

결과는 4000입니다.

2021/01/13 21:26

이준우

def find8(n):
    length = len(str(n))
    count = 0
    high = n // pow(10, length - 1)
    if n > 10:
        if high < 8:
            count = high * (length - 1) * pow(10, length - 2)
        elif high == 8:
            count = high * (length - 1) * pow(10, length - 2) + n % pow(10, length - 1)
        else:
            count = high * (length - 1) * pow(10, length - 2) + pow(10, length - 1)
        return count + find8(n % pow(10, length - 1))
    else:
        if n > 8:
            return 1
        else:
            return 0

print(find8(10000))

정면돌파 해봤습니다. 저 함수에 뭘 넣던 넣어준 수보다 작은 수들의 8의 갯수를 세 줍니다. 10^n 보다 작은 수들의 8의 갯수 총합은 n * 10^(n-1)임을 이용했습니다.

재귀 호출로 n자리 수를 찾고, n-1, n-2 ... 1자리 수에서 8의 갯수를 찾아 모두 더합니다.

따라서 맨 앞자리가 8인 경우가 예외가 되는데, 어차피 n-1자리는 재귀 호출로 구해지니까 맨 앞자리가 몇번 있는지만 알면 됩니다.

예를 들어 84562인 경우 8이 맨 앞자리인 수는 4562번 나타나기 때문에 뒷자리를 더해 주도록 했습니다.

9인 경우는 10000번 나타나니까 이걸 더해줬구요

한자리인 경우는 지수가 -1이 되기 때문에 예외처리 해줬습니다.

python 3.9.1

2021/01/21 00:19

김민수

cnt = 0
for i in range(1,10001):
    A = str(i)
    cnt += A.count('8')

print(cnt)

2021/01/21 19:58

fox.j

/* 1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?

8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함) */

let count = 0

for (let i = 1; i <= 10000; i++) {
  for (let j = 0; j < String(i).length; j++) {
    String(i)[j] === "8" && count++
  }
}

console.log(count)

2021/01/22 15:30

ZE

count = 0 # 8의 개수 0개로 시작
for x in range(1,10000): # 1~10000까지 반복
    for i in str(x): # 해당 숫자를 문자열로 반환 , (Ex, 1234 이면 '1234'로 for문에 들어가면 '1','2','3','4' 로 반복)
        if i == '8': # 문자열로 반환된 숫자가 8이면
            count+=1 # 1개를 카운트해라
        else:
            continue # 없으면 다시 반복문

count

2021/01/25 08:26

김현수

(java)

  int count = 0;
  int sum = 0;

  for (int i = 1; i <= 10000; i++) {
        if (i % 10 == 8)
            count++;
        if ((i / 10) % 10 == 8)
            count++;
        if ((i / 100) % 10 == 8)
            count++;
        if (i / 1000 == 8)
            count++;
         sum = count;
    }
    System.out.println("sum : " + sum)

2021/01/26 11:33

유병현

count=0

for x in range(1,10001):
  str1=str(x)
  k = str1.count('8')
  count+=k

print(count)

2021/01/28 22:07

장래희망파이썬마스터

nums = []

for i in range(1, 10000 + 1):
    nums.extend(list(str(i)))

print(nums.count('8'))

2021/01/31 16:46

Ha

4000

2021/02/16 11:41

Lee Young-Sup

count = 0

for i in range(1, 10001):
    if '8' in str(i):
        count += str(i).count('8')
print(count)

2021/02/16 13:15

pathworker

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
    int cnt=0;
    for(int i=1; i<10001; i++)
    {
        for(int j=0; j<5; j++)
        {
            if ((int)(i/pow(10,j))%10==8)
                cnt++;
        }
    }
    cout<<cnt<<endl;
    return 0;
}

C++시작한 코린이입니다...

2021/02/17 23:39

JM

print(str(list(range(1,101))).count('8'))

2021/02/20 01:18

­장태호 / 학생 / 원자핵공학과

num = ''
for i in range(1, 10000+1):
    num+=str(i)
print(num.count('8'))

2021/02/20 16:03

asdfa

count=0

for i in range(1,10001):
    for x in str(i):
        if x == '8':
            count+=1

print(count)


2021/03/13 10:36

최우진

c로 풀었읍니다~```

include

int main(void) {

int i, cont, a, b, c, d;

cont = 0;

for(a=0; a<=9; a++){
    for(b=0; b<=9; b++){
        for(c=0; c<=9; c++){
            for(d=0; d<=9; d++){
                if(d == 8){
                    cont += 1;
                }

                if(c == 8){
                    cont += 1;
                }

                if(b == 8){
                    cont += 1;
                }

                if(a == 8){
                    cont += 1;
                }

            }
        }
    }
}

printf("%d", cont);

} ```

먼가 위의 넥슨 입사문제랑 비슷해서 빠르게 풀엇네영

사실 사고력을 요하는 문제이지만

결국 컴퓨터로 노가다 돌린거랑 마찬가지라... 부끄럽습니다.

2021/03/13 16:41

모아민

#include <stdio.h>  //printf
#include <math.h>   //pow

int i, t, y, result;
void find8(int x);

int main()
{
    for (i = 1; i < 10000; i++)
        find8(i);

    printf("8의 개수 : %d", result);
    return 0;
}

void find8(int x) {
    for (t = 0; t < 4; t++) {
        y = (x % (10 * (int)pow(10, t))) / (1 * (int)pow(10, t));   // (X % 10) / 1 = 일의 자리수, (X % 100) / 10 = 십의 자리수
        if (y == 8) //해당 자리수가 8이면 result + 1
            result += 1;
    }
}

C를 이용해 작성했습니다. 아래는 입력받은 수까지 8의 개수를 구할 수 있도록 작성했습니다.

#include <stdio.h>  //printf
#include <math.h>   //pow

int i, t, cnt, result;
int n, x, y;
void find8(int x, int y);

int main()
{
    printf("1이상의 수를 입력해 주세요 : ");   // 정수 입력
    scanf_s("%d", &n);

    i = n;  // 입력받은 정수의 자릿수 구하기
    while (i > 0) {
        i /= 10;
        ++y;
    }

    for (i = 1; i < n; i++)
        find8(i, y);

    printf("8의 개수 : %d", result);
    return 0;
}

void find8(int x, int y) {
    for (t = 0; t <+ y; t++) {
        cnt = (x % (10 * (int)pow(10, t))) / (1 * (int)pow(10, t)); // (X % 10) / 1 = 일의 자리수, (X % 100) / 10 = 십의 자리수
        if (cnt == 8)   //해당 자리수가 8이면 result + 1
            result += 1;
    }
}

2021/03/16 21:41

argo

count = 0
for i in range(1, 10000):
    if "8" in str(i):
        for j in str(i):
            if int(j) == 8:
                count += 1
print(count)

<파이썬 3>

[결과] 4000

2021/04/05 09:24

Ruo Lee

' '.join(map(str, range(1, 10001))).count(str(8))

2021/04/07 11:06

hezuk

print("".join([str(i) for i in range(10001)]).count("8"))

결과 4000

2021/04/20 15:10

와장창

int totalCount = 0;
for(int i=1; i<=10000; i++) {
  String number = Integer.toString(i);
  String[] strArray = number.split("");
  //8이포함될경우
    for(String s : strArray) {
      if(s.equals("8")) {
      totalCount++;
    }
  }
}
System.out.println(totalCount);

2021/04/26 14:52

jaesung kim

def count8(start,end,search_no):
    buf=""
    for i in range(int(start),int(end)+1):
        buf=buf+str(i)
    return buf.count(str(search_no))

count8(1,10000,8)

2021/04/27 09:34

최태호

cnt = 0
for i in range(1, 10000):
    for k in str(i):
        if k in '8':
            cnt += 1
print(cnt)

2021/04/28 16:48

임동열

str_Num = [int(x) for i in range(10001) for x in str(i) ]

print(f'8의 개수는 ', str_Num.count(8), '개 입니다.')

2021/04/29 11:05

bravesong

sum(list(map(lambda i: i.count('8'), [str(i) for i in range(10000)])))

2021/04/30 13:23

songci

times = 0
for i in range(10000+1):
    times += str(i).count('8')
print("총",times,"번")

2021/05/23 16:38

ss2663

l = []

for i in range(1,10000):
    l.append(str(i).count('8'))
print(sum(l))

2021/05/24 14:31

약사의혼자말

count = []

for x in (range(1, 100)):
  for i in str(x):
    count.append(int(i))

print(count.count(8))


4

2021/05/26 21:47

jaesik

public class problem1 {
    public static void main(String[] args) {
        int count = 0;
        int[] arrays01 = new int[5];

        for (int i = 0; i < 10; i++) {
            arrays01[1] = i;
            for(int j = 0; j < 10; j++) {
                arrays01[2] = j;
                for(int k = 0; k < 10; k++) {
                    arrays01[3] = k;
                    for(int l = 0; l<10; l++) {
                        arrays01[4] = l;
                        for(int i2 = 1; i2<5; i2++) {
                            if(arrays01[i2] == 8) {
                                count += 1;
                            }
                        }
                    }
                }
            }
        }
        System.out.println(count);

2021/05/27 10:05

박준영

public class CountingEight { public static void main(String[] args) { for (int i=0; i<=10000; i++){ searchEight(i); } System.out.println("1에서 10,000 사이에 존재하는 8의 개수는? "+count); } private static int count = 0; public static void searchEight(int num){ if (num%10==8) count++; if (num>10) searchEight(num/10); } }

2021/05/28 21:26

니나노

%%timeit str(list(range(1, 10001).count('8') ===== count = 0 for i in range(10001): if '8' in str(i): count += stri(i).count('8') count ==== str([i for i in range(10001]).count('8')

2021/06/04 11:25

Jayden Jeong

count=0
for i in range(1,10001):
    for j in range(len(str(i))):
        if str(i)[j]=='8':
            count+=1
print(count)

2021/06/29 19:04

김민준

sum([str(x).count('8') for x in list(range(1,10001))])

2021/07/03 14:57

kim ih

lst = []
eight = "8"
for i in range(1,10001):
    for m in str(i):
        if eight == m:
            lst.append(int(m))
print(lst.count(8))

2021/07/15 16:29

billy han

#codingdojing_google_count8

#1~9999 -> 999까지의 8의 숫자를 세고 8개수 * 10 + 1000(8000 대 숫자)

count = 0

for num in range(1,1000):
    for i in str(num):
        if i == '8': count += 1

print(count*10 + 1000)

###### 줄여보자
#생각해보니 각 자리수의 이 있는 경우, 0~999까지 총 1000개씩.. 따라서 1000개 * 4 = 4000개

print(str(list(range(1,10000))).count('8')) ## 내부값이 그냥 하나의 string 타입..

2021/07/18 18:28

Jaeman Lee

result = 0
for i in range(1, 10001):result += str(i).count("8")
print(result)

한줄코드 연습한다...

2021/07/18 18:43

Annoymouse

파이썬 3.8.10으로 작성했습니다.

print(sum([sum([1 for a in str(x) if a == '8']) for x in range(1, 10000)]))

2021/07/30 16:09

baek choi

def count():
    count = 0
    for n in range(1, 10001):
        for i in str(n):
            if i == '8':
                count += 1
    print(count)

count()

2021/07/30 23:08

김준규

합계=0
숫자_나열=0
for i in range(1,10001):
   숫자_나열=str(숫자_나열)+str(i)
print(str(숫자_나열).count('8'))

2021/08/08 23:32

Percy

count = 0
for i in range(1,10000):
  count += str(i).count('8')
print(count)

2021/08/11 20:42

KiRist

sum([str(x).count('8') for x in range(1,10001)])

2021/08/15 19:57

trim39r

eight = 0 for n in range(1,10001): n_list = list(map(int, str(n))) eight += n_list.count(8)

print(eight)

2021/08/16 16:23

김동현

파이썬으로 작성하였습니다.

temp = []
for i in range(1,10000):
    for j in str(i):
        temp.append(int(j))
print(temp.count(8))

개선할 수 있도록 코드 리뷰 부탁드립니다.

2021/08/16 17:05

브로킴

package justStudying;

public class test1_20210818 {

    public static int sol(int num) {
        int ans = 0;
        String numS = Integer.toString(num);

        for(int i=0; i<numS.length(); i++) {
            switch(numS.substring(i,i+1)) {
            case "8":
                ans++;
                break;
            default:
                break;
            }
        }

        return ans;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int ans = 0;
        for(int i=1; i<=10000; i++) {
            ans += sol(i);
        }

        System.out.println(ans);
    }

}

2021/08/18 20:29

이병호

print(str([x for x in range(1,10000)]).count("8"))

2021/08/22 15:46

//python

x = ""
for i in range(10000+1):
    x += str(i)
print(x.count("8"))

2021/08/26 15:42

박대선

count = 0
for x in range(1,10000):
    for i in str(x):
        if i == "8":
            count += 1

print(count)

2021/08/26 16:04

코딩버거

a = list(range(1,10000))
b =''
for row in a:
    b = b + str(row)

print(b.count('8'))

2021/09/11 15:34

Beom Yeol Lim

sum=0
for i in range(1,10001):
    x=str(i).count('8')
    sum +=x
print(sum)

2021/09/20 16:16

ninanino

sum([len([num for num in str(x) if num=='8']) for x in range(1,10001)])

2021/09/20 21:31

이성연

print('he')

2021/09/21 11:02

sdfwerdg

answer=0
for i in range(8,10000):
  answer+=str(i).count('8')
print(answer)

2021/09/21 11:21

sdfwerdg

def find_8():
    cnt = 0
    for i in range(1,10001):
        cnt += str(i).count('8')
    return cnt

if __name__ == '__main__':
    print(find_8())

2021/09/21 18:40

서현준

void main()
{   
    int sum = 0;
    for (int i = 1; i <= 10000; i++)
    {
        char* ntos = new char[5];
        sprintf(ntos, "%d", i);
        int len = strlen(ntos);
        for (int j = 0; j < len; j++)
        {
            sum += ntos[j] == '8' ? 1 : 0;
        }
    }
    cout << sum;
}

2021/10/07 13:55

aozora18

print(str(list(range(10000))).count('8'))

보고 한 건 아닌데 이미 똑같이 푸신 분이 많네요.

2021/10/12 21:59

LSW

mylist=[]
cnt=0
for i in range(1,10000):
  for j in str(i):
    if j=='8':
      cnt+=1
  mylist.append(cnt)
  cnt=0

print(sum(mylist))

너무 단순하게 푼 것 같다...ㅜ.ㅜ

2021/10/19 17:53

ottato

static void count8(int x) {
        int count = 0;
        for(int i = 1; i <= x; i++) {
            for(int j = 0; j < (i+"").length(); j++) {
                if((i+"").charAt(j) == '8')
                    ++count;
            }
        }
        System.out.println(count);

    }

    public static void main(String[] args) {
        count8(10000);
    }

2021/10/24 19:19

박대현

var result = 0;

for(var i = 1; i <= 10000; i++) {
    var eight = i.toString();

    if(eight.indexOf(8) > -1) {
        for(var j = 0; j <= eight.length; j++) {
            if(parseInt(eight[j]) == 8) {
                result ++;
            }
        }
    }
}

2021/11/10 16:24

KHH Coder

str([i for i in range(1,10001)]).count('8')

2021/11/22 11:42

황성민

var count = 0;

for(i=1; i<=10000; i++) {
    var arr = i.toString().split("")
    for(j=0; j<arr.length; j++) {
        if(arr[j] === "8") count++
    }
}
console.log(count)

2021/11/23 16:09

유정효

public class Main {
    public static void main(String[] args) {
        int ans = 0;
        for(int i=0;i<10000;i++){
            int copy = i;
            while (copy != 0)
            {
                if(copy % 10 == 8 )  ans++;
                copy /= 10;
            }
        }        
        System.out.println(ans);
    }
}

2021/12/06 22:30

김형호

n8 = 0
for i in range(1,10001) :
    arr = list(map(int,"".join(str(i))))
    if 8 in arr :
        n8 += arr.count(8)


print(n8)

2021/12/19 12:06

양캠부부

t=0
for i in range(10000):
    s = [int(i) for i in str(i)]
    if 8 in s:
        t+=s.count(8)
print(t)

2021/12/23 18:03

김현수

sum(map(int, [str(x).count('8') for x in range(1,10001) if str(x).count('8') != 0]))

2021/12/27 23:16

bryn0726

numbers = []

for x in range(1, 10001):
    numbers.append(x)

numbers_total = ["".join(map(str,numbers))]
print("8이 몇번 들어가니?: ", numbers_total[0].count('8'))

# 한줄로 해버리깅~~
a = "".join(str(x) for x in range(1, 11)).count('8')
print(a)

2022/01/03 16:20

jenny

class Total8
{
    public static void main(String [] args)
    {
        int count=0;

        for(int i=1; i<10001; i++)
        {
                if(i/1000 ==8) // 천의 자리
                count++;

                if((i/100)%10 == 8) // 백의 자리
                count++;

                if((i/10)%10 ==8) // 십의 자리
                count++;

                if(i%10 ==8)// 일의 자리
                count++;

         }

        System.out.println("8의 총 개수 : "+ count);

    }
}

2022/01/04 09:56

networker


count_8 = 0

for num in range(1,10000):
    for num_str in str(num):
        if '8' == num_str:
            count_8 += 1

print(count_8)


2022/01/04 17:00

강태호

count=0

def counting(i):
    for i in str(i):
        if i=="8":
            global count
            count+=1

for i in range(1,10001):
    counting(i)

print(count)

2022/01/07 14:11

BANG

python 3.x

sum([str(v).count('8') for v in range(10000)])

2022/01/09 20:13

­김태경 / 학생 / 농림생물자원학부

cnt = 0

for n in range(1, 10001): for i in str(n): if int(i) == 8 : cnt += 1

print(cnt)

2022/01/18 12:44

배시원

count_8 = lambda x: str(x).count('8')
print(sum([count_8(x) for x in range(10001)]))

2022/01/28 11:05

로만가

eight = 0
for i in range(1, 10001):
    i = str(i)
    for item in range(len(i)):
        if '8' in i[item]:
            eight += 1

print(eight)


2022/01/28 20:39

Kya-Ha

count = 0

for i in range(10001): count += str(i).count('8')

print(count)

2022/02/11 00:18

엄태용

package org.javaturotials.ex; import java.util.*;

public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count=0; for(int i=1; i<10000; i++) { String a = String.valueOf(i); String[] arr = new String[a.length()]; arr=a.split(""); for(int j=0; j<arr.length; j++ ) { if(Integer.valueOf(arr[j])==8) { count++; } } } System.out.println(count); } }

2022/02/17 21:08

Kkubuck

package org.javaturotials.ex; import java.util.*;

public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count=0; for(int i=1; i<10000; i++) { String a = String.valueOf(i); String[] arr = new String[a.length()]; arr=a.split(""); for(int j=0; j<arr.length; j++ ) { if(Integer.valueOf(arr[j])==8) { count++; } } } System.out.println(count); } }```{.java} package org.javaturotials.ex; import java.util.*;

public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count=0; for(int i=1; i<10000; i++) { String a = String.valueOf(i); String[] arr = new String[a.length()]; arr=a.split(""); for(int j=0; j<arr.length; j++ ) { if(Integer.valueOf(arr[j])==8) { count++; } } } System.out.println(count); } } ```

2022/02/17 21:09

Kkubuck

def count_8(a):
    count8=0
    for s in str(a):
        if s=='8':
            count8+=1
    return count8
print(count_8(8088))

sum=0
for i in range(1,10001):
    sum+=count_8(i)
print(sum)

4000

2022/03/01 18:02

코딩초보박영규

num=0
for i in range(1,10001):
  for t in str(i):
    if t=='8':
      num+=1
    continue
print(num)

2022/03/02 13:28

김재민

#include <iostream>

int main() {
    int count = 0, i = 1;
    while (i <= 10000) {
        int n = i;
        while (n != 0) {
            if (n % 10 == 8) count++;
            n /= 10;
        }
        i++;
    }
    std::cout << count;
}

2022/03/02 23:48

YEON

쉽게 생각하면, 0000~9999까지 각 자리수마다 0~9까지 가능한 것이니, 0~9까지 숫자가 모두 동일한 갯수 만큼 나온다는 것을 알 수있습니다.

그럼 총 10,000가지 숫자가 각각 4자리 이기 때문에 전체 들어가는 숫자의 갯수는 4만개가 되고, 이를 10으로 나누면, 4000이 됩니다.

2022/03/07 18:07

김지섭

def to_count_num(num, max_num):
    num_mat = [int(k) for i in range(1, max_num + 1)
               for k in str(i)]
    return num_mat.count(num)

num = input('카운팅하기를 원하는 숫자가 무엇입니까? : ')
max_num = input('숫자 범위의 최대값을 입력해주세요. : ')
print('1 ~ ' + max_num + ' 범위에서 숫자 ' + num + '의 개수는 ' + str(to_count_num(int(num), int(max_num))) + '개 입니다.')

2022/03/08 16:18

고양이

a = list(str(n) for n in range(1,10000))
b = ''.join(a)
print(b.count(str(8)))

2022/03/14 22:18

박건호

lst = [str(i) for i in range(1,10001)]
count = 0

for i in lst:
    if '8' in i:
        eight = i.count('8')
        count += eight

print(count)

2022/03/16 06:04

Jaehyun Shin

count = 0
for num in range(1, 10001):
  if '8' in str(num):
    for digit in str(num):
      if digit == '8':
        count += 1
print(count)

2022/03/23 00:30

Charles

result = 0
for i in range(1,10001):
    result = result + str(i).count("8")

2022/03/25 23:38

무기

print(sum([str(x).count(str(8)) for x in range(0,10000)]))

결과값: 4000

다양한 접근이 가능하다는 걸 배우는 것 같습니다. 감사합니다~

2022/03/28 14:50

Jongjun Lee

su=0 for i in range(10001): for j in str(i): if j=='8': su+=1 print(su)

2022/04/11 16:45

yunjae

count = 0
for i in range(1, 10000) :
  for k in str(i) :
    if k == "8" :
      count += 1
print(count)

2022/05/07 13:17

나유진

print(dic[8]){.python} dic={i:0 for i in range(10)} print(dic) for i in range(10000): for j in str(i): dic[int(j)]+=1 print(dic[8])

2022/05/07 18:16

yunjae

print(count){.python} count=0 for i in range(1,10001): for j in str(i): if j=='8': count+=1 print(count)

2022/05/07 18:18

yunjae

s=""
for i in range(1,10001):
    s+=str(i)
print(s.count('8'))

2022/05/07 18:21

yunjae

count = 0
for i in range(1, 10001):
  s = str(i)
  for i in s:
    if i == '8':
      count += 1
count

2022/05/11 09:02

이승훈

i = 0
num = 0

for i in range(10001):
    for tp in str(i):
        if tp == '8':
            num += 1

print("Total number of 8 is " + str(num))

2022/05/21 20:48

Louie Yang

자바로 풀어보았습니다.

import java.util.Scanner;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        ArrayList<Integer> digits = new ArrayList<>();
        int n, i=1, count8=0;

        while(true) {
            System.out.println("자연수 n을 입력하시오:");
            n = scan.nextInt();

            if(n<1) {
                System.out.println("잘못 입력하셨습니다.\n");
            }else {
                break;
            }
        }

        while(i<=n) {
            int j=i;

            while(j>0) {
                digits.add(j%10);
                j /= 10;
            }

            for(j=0;j<digits.size();j++) {
                if(digits.get(j)==8) {
                    count8+=1;
                }
            }

            digits.clear();
            i++;
        }

        System.out.println(String.format("1부터 %d까지 8이라는 숫자는 %d번 나옵니다. \n", n, count8));
    }
}

2022/06/06 18:08

유로

count = 0
for i in range(10000):
    for x in str(i):
        if x == '8':
            count += 1


count
4000

2022/06/12 22:14

김시영

count=0
for i in range(10001):
    for num in list(str(i)):
        if num=="8":
            count+=1
print(count)

4000 나왔습니다. 한줄로도 할수있었네요ㄷㄷㄷ

2022/06/20 14:52

김정욱

num_list = [ ','.join(str(i)).split(',') for i in range(1,10001) ]
num_sum =sum(num_list, [])
num_sum.count(str(8))

파이썬입니당

2022/06/20 18:50

Hote

sum(str(x).count('8') for x in range(1,10001))

2022/06/23 15:33

YOUNGWOO SEO

print(sum([str(x).count('8') for x in range(1, 10001)]))

2022/06/24 09:23

mimeman

벽에 0000부터 9999까지 적어본다고 가정하면 수 하나에 4개의 숫자가 있고 수가 총 만개이므로 4만개의 숫자가 있고 0부터 9까지 같은비율이니 4만을 10으로 나누면 4천개 ! 그러므로 4천개

번외로 8 자체를 포함하지 않는 수의 갯수는 6561 이다! 이는 □□□□ 각 네모가 자릿수라고 생각하면 각 네모에는 8을 제외한 0,1,2,3 4,5,6,7,9 인 9가지의 숫자가 들어갈수 있기때문에 9^4 인 6561이 된다.

# 0부터 9999까지 8이 안들어가는 수 개수
alist = []
cc = 0
for ii in range(10000):
    c = 0
    for i in str(ii):
        if i == '8':
            c = 1
    if c == 0:
        cc += 1
print(cc)

2022/07/04 16:02

Tae Joo

nums = str([ x for x in range(1,10001) ])
print(nums.count('8'))

파이썬 3.8.5

2022/07/10 20:47

Estelle L


num_8 = 0

for num in range(1, 10001):                   #num = 1~10000까지의 숫자를 의미
    number = list(map(int, str(num)))

    result = number.count(8)                  #number 리스트 안에 8의 갯수를 파악

    num_8 += result                           #8의 숫자만큼 합산

print(num_8)

2022/07/17 15:29

박종훈

su = 0

for i in range(1,10001): i = str(i)

for j in i:
    if j == "8":
        su += 1
    else:
        continue

print(su)

2022/07/20 22:44

권회준

y = str(([x for x in range(1,10001)]))
y.count("8")

2022/07/25 16:25

JC YUN

import java.util.Scanner;

public class Problem3 {

    static void numberCounter(int n, int m) {
        StringBuilder line_has_m = new StringBuilder();
        StringBuilder line_nhas_m = new StringBuilder();

        for (int i=1; i<n+1; i++) {
            line_has_m.append(i);
        }
        String x = line_has_m.toString();  //세고자 하는 숫자 m이 표함된 숫자열


        String[] temp = x.split(String.valueOf(m));
        for (String s : temp) {
            line_nhas_m.append(s);
        }
        String y = line_nhas_m.toString(); //세고자 하는 숫자 m이 제거된 숫자열

        System.out.println("정답: "+(x.length()-y.length())+" 개 입니다.");
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("1부터 몇까지? -> ");
        int num1 = sc.nextInt();
        System.out.print("세고 싶은 숫자는? -> ");
        int num2 = sc.nextInt();

        numberCounter(num1, num2);
    }

}

2022/08/09 15:30

백진성

count = 0
for i in range(1,10001):
    for j in str(i):
        if j == '8':
            count += 1
print(count)

2022/08/15 14:25

강TT

total=[]
for i in range(1,10000):
    temp_num=[int(a) for a in str(i)]
    total=total+temp_num
num_of_8=total.count(8)
print(num_of_8)

2022/08/18 12:49

나무늘보

def counter8(x=0,y=10):    
    count1=0
    for a in range(x,y):
        for b in str(a) :
            if b == '8' : count1 += 1
    print(count1)
counter8(1,10000)

2022/08/18 13:36

쫑이아빠

count = 0

for i in range(1,10001):
    for k in str(i):
        if int(k) == 8:
            count += 1

print(count)

2022/08/20 20:23

황정현

count8 = {8:0}

for i in range (1,10001):
    for x in str(i):
        if int(x) == 8:
            count8[8] +=1

print (count8)

2022/09/15 13:07

최동진

public class Q3 {
    public static void main(String[] args) {
        int count=0;
        for(int i=1;i<=10000;i++) {
            for(int j=0;j<Integer.toString(i).length();j++) {
                if(Integer.toString(i).charAt(j)=='8') {
                    count++;
                }
            }
        }
        System.out.println(count);
    }
}

2022/09/21 10:19

김민중

count = 0
for i in range(10000):
    a = str(i)
    if '8' in a:
        for j in range(len(a)):
            if a[j] == '8':
                count += 1

print(count)

2022/09/30 15:45

Jaeyoung Moon

let count = 0;
let str;
for (let i = 1; i < 10001; i++) {
  str = String(i);
  for (let j = 0; j < str.length; j++) {
    if (str[j] === '8') {
      count += 1;
    }
  }
}

2022/10/06 14:38

이지형

print(sum([len([x for x in str(i) if x == '8']) for i in range(1, 10000)]));

python 3.10.8 리스트 내포 스타일

2022/10/22 11:17

마운틴

파이썬입니다.

count8 = 0
for i in range(10001) :
    for j in str(i) :
        if j == "8" :
            count8 += 1
print(count8)

2022/10/26 12:46

ㅇㅇ

sum(str(i).count('8') for i in range(1,10000))

2022/11/04 14:36

stubborngastropod

Python. 정답은 4000. 습관적으로 for 반복문을 사용했는데, 리스트를 전무 문자열로 바꾼 다음에 개수를 세는 방법도 있군요..! 다들 대단...!

eight_sum=0
for i in range (1, 10001):
    a=str(i) #int인 i를 문자열(str)로 전환
    b=a.count('8') #count 함수로 문자열 내 8의 개수 확인
    eight_sum+=b
print(eight_sum)

2022/11/09 16:46

Frye 'de Bacon

1 부터 10000까지가 정수라는 말이 없으니까 무한대가 아닐까요

2022/11/24 17:32

김진용

파이썬입니다

for i in range (1~10000)

count+=str(i).count('8')

print(count)

4000나왔습니다

2022/12/01 17:08

조랭이떡

cnt = 0
for i in range(10000):
    for j in range(len(str(i))):
        if int((str(i))[j]) == 8:
            cnt += 1
print(cnt)

python

2023/01/11 14:18

마라떡볶이

sum=0
for i in range(1, 10001):
    for j in str(i):
        if j=='8':
            sum+=1
print(sum)

2023/01/27 00:09

김민주

str(list(range(10000))).count('8')

2023/01/29 10:50

심유진

num8 = 0
for i in range(1,10001):
    str_i = str(i)
    for x in str_i:
        if x == '8':           
            num8 += 1
print(num8)                  

2023/02/05 14:47

제작자

  const checkEight = (number) => {
  let answer = 0
  for(let i = 1; i <= number; i++){
    let numToStr = String(i)
    let numArr = Array.from(numToStr)
    if(numArr.includes('8')){
        for(let i of numArr){
            if(i === '8'){
                answer++
            }
        }

    }else continue
  }
    return answer
}

2023/02/19 19:28

sooyoung159

count=0
for i in range(1,10001):
    for a in str(i):
        if a=='8':
            count+=1
print(count)

2023/02/22 14:56

최민우

input을 10,000으로 받고, check8이라는 배열을 생성합니다. fill을 사용해 모두 0으로 채워 넣은 후, map을 활용해 index값으로 늘리면서 10,000까지 들어 있는 배열을 만들었습니다.

이후 문자열로 변환 후 모든 숫자를 split("")하였습니다. 이후 filter를 사용해 "8" 값을 찾아냈고 길이만큼 출력했습니다. (숫자는 split("")을 할 수 없습니다.)

let input = 10000;

let check8 = Array(input).fill(0).map((v, i) => i);

let result = check8.toString().split("").filter((v) => v === "8").length;

console.log(result);

2023/03/10 14:42

KUKJIN LEE

maxNum=10000
count=0
for i in range(1,maxNum+1):
    for j in str(i):
        if j=='8':
            count+=1
print(count)

2023/03/11 19:23

Sol Song

print (str(list(range(1,10001))).count('8'))

2023/03/20 13:31

최준하

Array(10000).fill(0).map((v, i) => i).toString().split('').filter(v=>v==='8').length

2023/03/21 17:18

유민지

print(''.join(map(str, [i for i in range(1, 10001)])).count("8"))
>>> 4000

풀고보니 쓸데없이 리스트 컴프리헨션을 썼네요.^^;

2023/03/25 13:37

관산정

count = 0

for i in range(1, 10000):
    if i < 10 and i % 8 == 0:
        count += 1
    elif i < 100:
        if i // 10 == 8:
            count += 1
        if i % 10 == 8:
            count += 1
    elif i < 1000:
        if i // 100 == 8:
            count += 1
        if (i % 100) // 10 == 8:
            count += 1
        if i % 10 == 8:
            count += 1
    else:
        if i // 1000 == 8:
            count += 1
        if (i % 1000) // 100 == 8:
            count += 1
        if (i % 100) // 10 == 8:
            count += 1
        if i % 10 == 8:
            count += 1

print(count)

2023/03/31 15:04

용맨달려

max_len = 10000
count = 0
for i in range(max_len):
    for i in str(i):
        if i == '8':
            count += 1
print(count)

2023/03/31 17:42

HoHyeon Kim

#str로 변환하여 추출하면 더 빠를 것 같다고 생각했습니다

counting = 0
for n in range(1, 10001):
    new = str(n)
    for i in new:
        if i == "8":
            counting += 1

print(counting)

2023/04/03 11:34

심영채

line2 = [i for i in range(1,10001)]
k=0
for i in line2:
    i = str(i)
    k +=i.count('8')

print(k)

2023/04/05 22:13

정원영

def count_eight(number):
    count = 0
    for idx in str(number):
        if idx == "8":
            count += 1
    return count

count_list = []
for idx in range(10000):
    count_list.append(count_eight(idx))

print(sum(count_list))

2023/04/15 22:59

이준수

count8 = 0
for a in range(10001):
    for b in str(a):
        if b == '8':
            count8 = count8 + 1

print(count8)

2023/04/18 04:09

졸린하마

파이썬으로 푼 예시답변 입니다. 그냥 전부 리스트로 만든 다음 숫자를 각각 분리해서 '8'이 몇번 있는지 세줍니다. (count 사용) 그리고 sum2에 넣어서 끝냅니다.

sum2 = 0
for i in range(1, 10001):
    k = list(str(i)).count('8')
    sum2 += k
print(sum2)

2023/04/29 17:34

Chae Won Im

x = ''
for i in range(1, 10001):
    x = x + str(i)
x.count('8')    

2023/06/10 22:12

sjbyun

function solution(number) { let answer = 0; for (let i=0; i< number; i++) { answer += ([...String(i)].filter(v => v === '8').length); // console.log([...String(i)], [...String(i)].filter(v => v === '8').length); } return answer; }

console.log(solution(10000));

2023/06/21 21:16

홍힌기

num = 0

for i in range(10001):
  str_i = str(i)
  for character in str_i:
    if character == '8':
      num+=1
print(num)

2023/07/13 11:34

스탠리

element = []
count = 0
total_list = list(range(1,10000))
   for i in str(total_list):
      for j in str(i):element.append(j)
count = element.count("8")
print(count)

2023/07/21 10:19

siu yoon

n = 10000
cnt = 0

for i in range(10000):
    nLst = list(str(i))
    if '8' in nLst:
        cnt += nLst.count('8')

print(cnt)

2023/07/23 19:52

Hawk Lee

cnt_8 = 0
for num in range(1, 10001):
    for n in str(num):
        if n == '8':
            cnt_8 += 1
print(cnt_8)

2023/08/12 19:39

이광진

javascript 풀이입니다.

const answer = Array(10000).fill(0).map((v,i)=>i).join("").split("").filter(v=> v==='8');
rerturn answer.length;

2023/09/01 21:53

셔이

max_number = 10000 count_eight = 0

for i in range(1, max_number +1): j = i while True: temp_number = j % 10 if temp_number == 8: count_eight += 1 if j // 10 == 0: break j = j // 10

print(count_eight)

2023/12/18 11:03

박용규

let totCnt = 0; for(let i=1; i<10000; i++){ let item = i+''; for(let j=0; j<item.length; j++){ if(item.charAt(j) == '8'){ totCnt++; } } } console.log("1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가? : " , totCnt);

2024/01/09 01:47

CoffeeAndSweet

eight = 0
for i in range(10000):
    a = str(i)
    eight += a.count('8')
print(eight)

2024/02/03 14:43

리리

print(str(list(range(1,10001))).count("8"))

2024/02/21 16:10

버거킹

eight_count=0
for a in range(1,10001):
    number=str(a).count('8')
    eight_count+=number
    number=0
print(eight_count)

2024/02/24 10:33

박성우

def count(num):
    count = 0
    if '8' in str(num):
        for i in str(num):
            if i == '8':
                count += 1
    return count

total = 0
for i in range(1, 10001):
    total += count(i)
print(total)

2024/02/24 22:19

야옹

cuantos_ocho = 0

for i in range(1, 10001):
    str_i = str(i)
    cuantos_ocho += str_i.count('8')

print(cuantos_ocho)

2024/03/12 15:00

만원

```{.java}

```public static void main(String[] args) {

          int max = 10000;
          int addResult = 0;
          int[] intResult = new int[5];

          for (int a = 1; a <= max; a++) {
                 String inputString = String.valueOf(a);
                 String[] result = inputString.split("");
                 for (int i = 0; i <result.length; i++) {
                        intResult[i] = Integer.parseInt(result[i]);
                        if (intResult[i] == 8) {
                               addResult = addResult + 1;
                        }
                 }
          }
          System.out.println("8 의 수 : " + addResult);

}

2024/04/01 11:39

지현

public static void main(String[] args) { Scanner sc = new Scanner(System.in); int max = 0; String maxInsert = ""; int addResult = 0; System.out.println("찾고자 하는 숫자와 범위를 입력해 주세요."); System.out.print("찾고자 하는 숫자 : "); int find = sc.nextInt(); System.out.print("범위 : "); maxInsert = sc.next(); max = Integer.parseInt(maxInsert); int[] intResult = new int[maxInsert.length()]; for (int a = 1; a <= max; a++) { String inputString = String.valueOf(a); String[] result = inputString.split(""); for (int i = 0; i <result.length; i++) { intResult[i] = Integer.parseInt(result[i]); if (intResult[i] == find) { addResult = addResult + 1; } } } System.out.println(find+" 의 수 : " + addResult); } } - 지현, 2024/04/01 11:47
count = 0
for i in range(1, 10001):  
    count += str(i).count('8')
print(count)

2024/05/30 18:32

김현빈


count = 0
list_num = []
for i in range(0, 10000): # 55
    list_num = list(str(i))
    print(list_num)
    for j in list_num:
        if '8' in j:
            count += 1

print(f"1부터 10,000까지 8이라는 숫자가 총 {count}만큼 나온다.")

2024/08/13 15:05

먼지

eight_num = 0

for n in range(1, 10000+1):
    n_str = str(n)
    eight_num += n_str.count('8')

print(eight_num)

2024/10/16 19:14

rgone6

# 1개의 8이 있을 경우: 예) XXX8(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 1개 할당하는 경우의 수는 조합으로 구함: C(4, 1) = 4!/1!(4-1)! = 4
# 경우의 수 x 9 x 9 x 9 x 8의 개수: 4 x 9 x 9 x 9 x 1 = 2916

# 2개의 8이 있을 경우: 예) XX88(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 2개 할당하는 경우의 수는 조합으로 구함: C(4, 2) = 4!/2!(4-2)! = 6
# 경우의 수 x 9 x 9 x 8의 개수: 6 x 9 x 9 x 2 = 972

# 3개의 8이 있을 경우: 예) X888(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 3개 할당하는 경우의 수는 조합으로 구함: C(4, 3) = 4!/3!(4-3)! = 4
# 경우의 수 x 9 x 8의 개수: 4 x 9 x 3 = 108

# 4개의 8이 있을 경우: 예) 8888(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 4개 할당하는 경우의 수는 조합으로 구함: C(4, 4) = 4!/4!(4-4)! = 1
# 경우의 수 x 1 x 8의 개수: 1 x 1 x 4 = 4
import math

total = 0

for n in range(1, 5):  # n: 8의 개수, 8이 없는 자리수: 4 - n
    cnt = math.comb(4, n)
    sum = cnt * 9**(4-n) * n
    total += sum

print("total = ", total)

2024/10/17 11:10

rgone6


Array(10000).fill(1).map((i,idx)=>i+idx).join("").split("8").length-1

2024/12/19 17:08

fsfsdfss1657

JAVA입니다.

package 구글_입사문제_중에서;

public class Main {

    public static void main(String[] args) {
        int count = 0;
        for (int i = 1; i <= 10000; i++) {
            String numStr = Integer.toString(i);
            for (Character c : numStr.toCharArray()) {
                if (c == '8') {
                    count++;
                }
            }
        }
        System.out.println(count);
    }

}

2025/01/17 21:51

박준우

'''
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?

8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)

'''
def examineNumber(repeat, num):
    total = 0
    for i in range(1, repeat + 1):
        total += str(i).count(str(num))  # 문자열 변환 후 count() 사용
    return total  # return으로 값 반환

# 실행
print(examineNumber(10000, 8))
#repeat = int(input("찾을 범위 입력 : "))
#num = int(input("찾을 숫자 입력 : "))
#examineNumber(repeat,num)

2025/01/31 04:24

구점팔

eight_cnt = 0

for i in range(10000):
  eight_cnt += str(i).count("8")

print(eight_cnt)

이미 print(str(list(range(10001)).count("8"))이 올라와 있어서 풀어서 하는 방법

2025/02/24 14:28

Dasol Lee

int cnt = 0;

        for(int i = 1; i <= 10000; i++) {
            String numStr = String.valueOf(i);
            for(char c : numStr.toCharArray()) {
                if( c == '8') {
                    cnt++;
                }
            }
        }

출력 4000

2025/03/14 13:57

Kideok KIM

count_8 = 0  
for i in range(1, 10001):
    count_8 += str(i).count('8')  
print(f"total: {count_8}")

파이썬 공부시작한 뉴비입니다 4000!

2025/03/18 14:12

hanarado

[Solved with Python]

def count_eights():
    answer = 0
    for number in range(1, 10001):
        answer += str(number).count('8')
    return answer

print(count_eights())

2025/10/28 23:04

습자

cnt=0

for i in range(1,10000):
    num=str(i)
    for j in num:
        if j=='8':
            cnt+=1

print(cnt)

2026/01/20 21:15

키자루

print(sum(str(x).count(str(8)) for x in range(1, 10001)))

2026/05/04 21:35

우영재

목록으로