이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

숫자 세기 알고리즘

0부터 9999까지 8을 포함하지 않는 수는 총 몇개일까?

8, 108, 888, 9998 등은 8을 포함하고 있는 수입니다. 111, 299, 4 등과 같은 수는 8을 포함하지 않는 수 입니다.

2022/07/11 21:15

Tae Joo

60개의 풀이가 있습니다.

print(int('10000',9))


0~9999(9진법)에 수가 몇 개 있느냐 즉 답은 10000(9진법)인 문제입니다.

2022/10/17 10:08

Lupin Arsene

천재적인 발상이네요! 배우고 갑니다 - Shiroha, 2023/01/17 19:58
근데... 답이 좀 틀린데요. 9진수에 대한 것은 아닌듯. - siu yoon, 2023/07/05 17:35
대박이네요 정말 - Tae Joo, 2023/08/29 15:18
print(len([ x for x in range(10000) if '8' not in str(x) ]))

결과: 6561

파이썬 3.8.5

2022/07/11 22:09

Estelle L

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/15 13:37

Tae Joo

count = 0
for i in range(0, 10000):
    a = list(str(i))
    if "8" not in a:
        count += 1
print(count)

파이썬으로 풀이해보았습니다.

2022/07/15 16:27

Jung

len([x for x in range(10000) if "8" not in str(x)])

2022/07/25 15:03

JC YUN

깔끔하네요! - 졸린하마, 2023/04/21 11:37
count=0
for i in range(10000):
    if "8" in str(i):
        count+=1
print(10000-count)

2022/07/26 17:12

김준성

a = []
for i in range(10000):
    if "8" not in str(i):
        a.append(i)
print(len(a))

2022/07/27 22:08

김범석

def res(s_num):
    re = 0
    for i in range(s_num+1):
        if '8' not in str(i):
            re += 1
    return re


print(res(10000))

2022/08/10 09:52

으랴랴

count = 0

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

print(count)

2022/08/17 13:49

Anjinyong

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

2022/08/18 19:57

kee

lst = []
z =1
while z <= 1000:
    print(z)
    if "8" in str(z):
        lst.append(z)
    else:
        pass
    z += 1
print(lst)
print(len(lst))

while문으로 화려하게 작성해보았습니다.

2022/08/19 21:18

별키

  1. 우선 해당 문제를 수학의 Modular 연산을 이해하는 것에 대한 출제 의도로 파악했습니다.
  2. 굳이 8이 아니더라도 1~9까지의 수가 검출되는 결과는 동일합니다.
  3. 3, 6, 9 게임처럼 해당 숫자가 있는 것을 파악 각 자리수에 8이 있는 숫자를 찾아야 합니다.
  4. 예를 들면 8은 (8 % 10) 으로 찾아지고, 80은 (80 % 100)으로 찾아집니다. 88은 (8%10)으로 먼저 찾아지겠네요
  5. 8 % 10 = 8, 80 %100 = 80, 800 % 1000 = 800....
#include <stdio.h>
#include <math.h>

// 숫자를 찾는 함수 입니다. 
int count_number(int input_number, int start_n, int end_n)
{
  // 8을 찾는 총  count입니다.
    int number_find_count = 0;

  // start_n + end_n의 개수입니다. 0부터 9999이니 총 10000 입니다.
    int total_count = end_n - start_n + 1;

    int result_count = 0;

  // 찾는 숫자는 1~9로 fix했습니다.
    if((input_number < 1 ) || (input_number > 10))
    {
        printf("Find Number range is from 1 to 9 \r\n");
        return -1;
    }

  // 0~9999의 숫자를 찾습니다.
    for(int i = start_n; i< end_n; i++)
    {
        for(int j = 0; j< 4; j++)
        {
      // pow라는 함수는 10지수승입니다. 10의 0은 1이고 10의 1승은 10, 2승은 100입니다.
      // 10, 100, 1000, 10000으로 나누면서 8이 발견하면 count를 증가하고 loop를 빠져나갑니다.

            int mod_value = pow(10, (j+1));
            int remainder  = input_number * pow(10,j);
            if((i%mod_value)==(remainder))
            {
                number_find_count++;
                printf("find value (%d) % (%d) == %(%d) \r\n", i , mod_value, remainder);
                break;
            }
        }
    }

    printf("A total %d of number(%d) from %d to %d were detected.\r\n", number_find_count ,input_number, start_n, end_n);
  // 8을 찾은 결과에서 숫자 전체 개수를 빼면 의도한 결과가 나옵니다.
    result_count = total_count - number_find_count;
    printf("There are %d numbers excluding %d. \r\n", result_count, input_number);
    return 0;
}

int main(int argc, char *argv[])
{
    count_number(8, 0, 9999);
    return 0;   
}

2022/08/20 21:32

michael Lee

count=0
for k in range(0,10000):
    if(not "8" in str(k)):
        count += 1
print (count)

2022/08/23 15:51

신정식

a = list(range(-1,10000))
c=10000 
for i in range(len(a)):
    b = list(str(i))
    if str(8)  in b:
        c-=1



print(c)

2022/08/23 23:53

허명재

Java는 없어서 이렇게 풀어봤습니다. 개선점이 있다면 답글 부탁드립니다.

public class NumberAlgorithm {

    private static final int MAX_NUM = 9999;

    public static void main(String[] args) {

        int resultMinus = 0;
        int i = 0;
        for (; i <= MAX_NUM; i++) { // 9999까지 Loop

            // break시작지점
            char[] digit = String.valueOf(i).toCharArray();

            for (int j = 0; j < digit.length; j++) { //  digit의 자리수 Loop
                if (digit[j] == '8') { // 8이 포함된 자리가 있다면 Minus 카운트 후 break
                    resultMinus++;
                    break;
                }
            }
        }

        System.out.println("[0~9999] 8을 포함하지 않는 결과 ::: " + (i - resultMinus)); // 0부터 9999까지의 숫자 개수 - 8포함된 숫자 개수
    }
}

2022/08/25 23:35

조용환

문제 풀이

# 숫자 세기 알고리즘

def foo():
    count = 0
    target = "8"
    for i in range(0, 10000):
        if target not in str(i):
            count += 1
    return count

print(foo())

2022/09/01 13:26

이경석

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

print (num_not_8)

2022/09/04 00:09

Buckshot

결과 : 6561 - Buckshot, 2022/09/04 00:09
cnt = 0
for i in range(0, 10000):
    s = f"{i}"
    if s.find('8') == -1:
        print(s)
        cnt += 1

print()
print("cnt: ", cnt)

2022/09/05 04:36

Park ChanWoo

print([1 if '8' in str(i) else 0 for i in range(10000)].count(0))

2022/09/10 16:52

고양이

count=0

for i in range(10000):

if not '8' in str(i):
    count+=1

print(count)

2022/09/14 16:55

이진영

# Codingdojang 274
total_list=[int(i) for i in range(0,10000)]
Exclude_eight=[int(i) for i in total_list if '8' not in str(i)]
print(len(Exclude_eight))

2022/09/14 21:27

나무늘보

count = 1

for i in range(1,10000) : while i > 0 : if i % 10 != 8 : i = int(i/10) elif i % 10 == 8 : count += 1 break

print(10000-count)

2022/09/15 15:45

IX

Python 3.10

def main():
    rst = len([i for i in range(10_000) if '8' not in str(i)])
    print(rst)


if __name__ == "__main__":
    main()

2022/10/04 17:37

mohenjo

a=0
for i in range(10000):
    if str(i).find("8") == -1:
        a += 1
print(a)

2022/10/14 13:44

Zikill_ Hide

b=list() for i in range(10**4): i=str(i) if "8" in i == False: b.append(i) len(b)

2022/10/20 11:03

지덕현

Python. 'not in'이면 간단하게 해결할 것을 괜히 복잡하게 생각해서 정규식까지 가져왔네요;;

import re
p=re.compile('8')
numbers=list(range(0,10000))
count=0
for number in numbers:
    if p.search(str(number)):
       pass
    else:
         count += 1
print(count)

2022/11/01 09:53

Frye 'de Bacon

result = 0
check = 0
for i in range(0,10000):
    k=str(i)
    check = 0 
    for j  in k:
        if int(j) == 8:
            if check ==0:
                result= result-1
                check = 1          
    result+=1
print(result)

2022/11/02 17:46

기경수

total = 0

for i in range(0,10000):
    if '8' in str(i):
        continue
    total+=1
print("0부터 9999까지 8을 포함하지 않는 수의 갯수 => "+str(total))

2022/11/03 21:31

피봇맨

숫자를 문자열로 취급해 8을 포함하는지 검사하는 방식이 아니라 숫자 형태로 검사하는 방식입니다. 일의 자리에 8이 있는지 검사하고 완료되면 일의 자리를 제거하고 그 다음(십의 자리를 검사했으면 백의 자리) 자리를 검사하는 방식입니다.

void _Test2()
    {
        string result = "";
        for (int i = 0; i < 10000; ++i)
        {
            int n1 = i % 10;
            if (n1 == 8)
            {
                result += i + ", ";
                continue;
            }

            int n2 = i / 10;
            n2 = n2 % 10;
            if (n2 == 8)
            {
                result += i + ", ";
                continue;
            }

            int n3 = i / 100;
            n3 = n3 % 10;
            if (n3 == 8)
            {
                result += i + ", ";
                continue;
            }

            int n4 = i / 1000;
            //n4 = n4 % 10;
            if (n4 == 8)
            {
                result += i + ", ";
                continue;
            }

            //if (s.Contains("8") == true)
            //    result += s + ", ";
        }
        Debug.Log(result);
    }

2022/11/04 15:59

피치

count = 0
for i in range(10000) :
    for j in str(i) :
        if j == '8' :
            count += 1
            break
        else :
            pass
print(10000 - count)

2022/11/07 13:44

ㅇㅇ

count=0
for a in range(10000):
    if(not '8' in str(a)):
        count += 1
print(count)

2022/11/18 13:44

JH CH

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

print(count)

2022/11/25 15:24

SANGJIN PARK

package project1.project;

import java.util.ArrayList;

class calculate {
    int usedata;
    int appearancenumber;
    ArrayList<Integer> datalist = new ArrayList<Integer>();
    public calculate(int data) {
        this.usedata = data;
    }

    public void cal() {
        for (int n=0; n<usedata; n++) {
            String q = String.valueOf(n);
            ArrayList<String> s = new ArrayList<>();
            for (int r = 0; r<q.length(); r++) {
                char aaa = q.charAt(r);
                String aa = String.valueOf(aaa);
                s.add(aa);
            }
            if (s.contains("8")) {
                int mmm;
            } else {
                datalist.add(n);
            }
        }
    }
    public ArrayList<Integer> returndata() {
        return datalist;
    }

}
public class project {
    public static void main(String[] arg) {

        calculate c = new calculate(10000);
        c.cal();
        ArrayList<Integer> result = c.returndata();
        System.out.println(result.size());
    }
}

java로 풀었습니다

2022/12/18 16:20

고태욱

0부터 세어야 하기 때문에 return에서 'end값에 1을 더한 값'에서 8이 포함된 개수를 빼야 합니다. 매개변수로는 (9999, 8)을 주었고 결과는 6561이 나왔습니다.

    public static long count(int end, int target) {
        return (end + 1) - IntStream.rangeClosed(0, end).filter(v -> (v + "").contains("" + target)).count();
    // return (end + 1) - (int) IntStream.rangeClosed(0, end).filter(v -> String.valueOf(v).contains(String.valueOf(target))).count();
    }

2023/01/25 08:38

Miracle Lee

include

int main() {

int sum = 10000;
for(int i=0;i<10000;i++){
    int temp = i;
    if(8000<=i && i<9000) sum -=1;
    else{
        i %= 1000;
        if(800<= i && i<900) sum -=1;
        else{
            i %= 100;
            if(80<=i && i<90) sum -= 1;
            else{
                i %= 10;
                if (i==8) sum -= 1;
            }
        }
    }
    i=temp;
}
printf("%d\n",sum);
return 0;

}

2023/03/27 17:15

김남현

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

2023/04/03 09:46

HoHyeon Kim

class FindNumber:

    def __init__(self,maxNum,findNum):
        self.maxNum  = maxNum
        self.findNum = findNum


    def searchNum(self):
        list = []
        print("최대숫자:" ,self.maxNum , "찾을 수:", self.findNum)
        for x in range(0, self.maxNum):
           tempValue= str(x)
           if tempValue.find(str(self.findNum)) >=0 :
               list.append(x)
              # print(f"{tempValue} is contained {self.findNum}")
        return list


fn= FindNumber(1000,8)
list = fn.searchNum()
print(list)

2023/04/21 10:55

Seokwoo Choi

print(len([i for i in range(10000) if str(i).count('8') == 0]))

2023/04/21 11:43

졸린하마

경우의 수 문제이므로 코딩없이 간단히 풀 수 있습니다..^^ 총 4자리의 숫자이고, 각 자리에 0, 1, 2, 3, 4, 5, 6, 7, 9의 9개의 숫자 중 하나가 올 수 있으므로 9x9x9x9를 계산하면 6561로 답을 구할 수 있습니다.

2023/05/01 14:46

Jisook

# 0-9999 중 8을 포함하지 않은 수 세기

noteight = 0
for i in range(10000):
    if "8" not in str(i):
        noteight += 1
print(noteight)

2023/05/10 15:30

띵띵동

print('0부터 9999까지 8을 포함하지 않는 수는 :')
cnt = 0
for i in range(0, 10000):
    if '8' not in str(i):
        cnt += 1

print(cnt)     # 6561

print('각 자리에 올 수 있는 수는 9 가지 : ',9**4)   # 6561

2023/05/23 20:15

insperChoi

num = 0
for i in range(0,9999):
    if i % 1 == 8:
        num += 1
    elif i % 10 == 8:
        num += 1
    elif i % 100 == 8:
        num += 1
    elif i % 1000 == 8:
        num += 1
print(10000-num)

2023/06/22 10:17

꽃우진

count = 0
for i in range(9999):
   if str(8) not in str(i):
      count += 1
print(count)

2023/07/05 17:31

siu yoon

count = 0

for i in range(10000):
  str_i = str(i)
  for num in str_i:
    if '8' in str_i:
      count+=1
      break

print(10000-count)

2023/07/12 19:49

스탠리

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

2023/07/18 06:34

Hawk Lee

print(len(set(a for a in range(0,10000) if a//1000 != 8 and a%1000//100 != 8 and a%100//10 != 8 and a%10 != 8)))

2023/08/10 15:33

이진성

result = 0
For i = 0 To 9999
    If InStr(i, "8") = 0 Then
        result = result + 1
    End If
Next i

2023/08/24 13:58

신현철

' 엑셀VBA
Sub TEST()
    Dim i As Long
    Dim cnt As Long

    cnt = 0
    For i = 0 To 9999
        If InStr(Format(i, "0000"), "8") = 0 Then
            cnt = cnt + 1
        End If
    Next

    MsgBox (cnt)
End Sub

2023/10/11 14:15

마귀할멈

a = []
for i in range(0,10000):
    if '8' not in str(i):
        a.append(i)
print(len(a))

2023/10/20 22:02

김예람

count = 0 for i in range (10000): i = str(i) if not "8" in i: count += 1 print(count)


2023/12/28 22:01

개발로연봉1억이꿈인고딩

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

2024/03/23 17:37

라구리

기존 파이썬 string기초만 이용하면

def do_not_provide_8_number(input_n):
    """
    input_n이 숫자고 그때 input_str이 8을 포함하는지 하지 않는지 판단한다. 
    8을 포함하면 true를, 포함하지 않으면 false를 리턴한다.
    """
    flag = False
    input_str = str(input_n)
    for i in range(len(input_str)):
        if input_str[i]=="8":
            flag = True
    return flag
count=0
for j in range(9999):
    flag = do_not_provide_8_number(j)
    count+=flag
print(count)

2024/05/09 22:35

오라이트

print(len(list(lambda x:x for x in range(1,10000) if "8"  not in str(x))))

2024/05/26 12:07

이현민

num = 0 count = 0

for num in range(0,10000): num_str = str(num) if '8' in num_str: num += 1 continue else: num += 1 count += 1

print(count)

2024/09/10 15:52

kittygame05

a = {i for i in range(0,1000) if '8' in str(i)}
len(a)

2024/10/13 19:02

송승민

# 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: 4 x 9 x 9 x 9 = 2,916

# 2개의 8이 있을 경우: 예) XX88(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 2개 할당하는 경우의 수는 조합으로 구함: C(4, 2) = 4!/2!(4-2)! = 6
# 경우의 수 x 9 x 9: 6 x 9 x 9 = 483

# 3개의 8이 있을 경우: 예) X888(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 3개 할당하는 경우의 수는 조합으로 구함: C(4, 3) = 4!/3!(4-3)! = 4
# 경우의 수 x 9: 4 x 9 = 36

# 4개의 8이 있을 경우: 예) 8888(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 4개 할당하는 경우의 수는 조합으로 구함: C(4, 4) = 4!/4!(4-4)! = 1
# 경우의 수 x 1: 1 x 1 = 1

# 0 ~ 9999: 총 10,000개 중에 8이 1개 이상 있는 경우는 2,916 + 483 + 36 + 1 = 3,439
# 0 ~ 9999: 총 10,000개 중에 8이 포함되지 않는 경우는 10,000 - 3,439 = 6561

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) 
    total += sum

print("total = ", total)
print("total_without_8 = ", 10000 - total)

2024/10/17 14:59

rgone6

cnt = 0 #8이 안 들어간 수

#무식하게 0부터 9999까지 반복해보자
for n in range(0,10000) :
    #자릿수 추출
    a = n // 1000
    b = (n % 1000) // 100
    c = (n % 100) // 10
    d = n % 10

    if a != 8 and b != 8 and c != 8 and d != 8:
    cnt += 1

print(cnt)

2024/11/04 14:56

김빛나

eightlist = [x for x in range(10000) if '8' not in str(x)]
print(len(eightlist))

2025/02/25 14:31

Dasol Lee

print(len([ x for x in range(10000) if '8' not in str(x) ]))

2025/03/26 19:58

김춘오

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

2025/08/21 21:41

허거덩

목록으로