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

1~1000에서 각 숫자의 개수 구하기

예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자

10 = 1, 0
11 = 1, 1
12 = 1, 2
13 = 1, 3
14 = 1, 4
15 = 1, 5

그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개

2016/04/06 22:12

hana11

+5 예시에서 1은 7개입니다. - 차우정, 2016/05/13 23:51

732개의 풀이가 있습니다.

count={ x:0 for x in range(0,10) }

for x in range(1,1001):
    for i in str(x):
        count[int(i)]+=1

print(count)

2016/05/14 16:57

[email protected]

정말 판타스틱하네요. - Shin gil sang, 2019/01/02 09:35
딕셔너리 이용한 코드 예술이네요 - 이명운, 2019/08/27 14:30
예술입니다. - Sean, 2019/12/19 18:24
문자열에 대해서도 for문을 사용할 수가 있군요.. for i in str():과 같이 쓰면 맨 앞 문자열부터 훑고 가는거였군요,! 또 하나 배워갑니당 - 코딩뚜, 2021/01/04 16:32
질문이 있습니다. count={ x:0 for x in range(0,10) } 에서 x:0의 의미가 뭔지요? - DongKyu Lee, 2021/06/08 11:52
저도 질문이 있습니다. count={ x:0 for x in range(0,10) } 라고 했는데, 이를 응용해서 "0" 부분도 for문을 이용해서 변경할수 있나요? variant= { x:y for x in range(0,10) for y in range(11,21 } 으로 하면 "y" 값이 "20"으로만 고정되서 나오네요 어떻게 해야 y 값을 11~20으로 할수 있을까요? - 가을아침, 2021/06/15 14:31
y 값을 변경하려면 x값을 함께 변경시켜야 합니다. 위의 방식으로 하면 먼저 만들어진 0:11은 그 후에 0:12로 바뀌고 마지막에 0:20으로 바뀐 후 1:11이 만들어지고 이것도 마지막에 1:20으로 바뀌게 됩니다. 결국 딕셔너리의 키 값은 같은 값이 하나만 존재할 수 있기 때문에 y의 마지막 값만 각 x에 할당됩니다. - ­박철희, 2021/09/13 11:23

파이썬3.4

from collections import defaultdict

d = defaultdict(int)
for n in range(1, 1001):
    for x in str(n):
        d[x] += 1

print(d)

2016/04/06 22:32

디디

int box[] = new int[10];//각 숫자를 저장할 공간
        for (int i = 1; i <= 1000; 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]++;//천의 자리
        }
        System.out.println(Arrays.toString(box));

2016/06/16 21:21

김 수영

깔끔합니다~ - 고요정, 2019/01/21 13:05

python 3.5.1+ 로 작성했습니다.

temp=[0,0,0,0,0,0,0,0,0,0] # 리스트 생성
for num in range(1,1001): #0~1000
  for tp in (str(num)): # 각 숫자를 배열로 취급하기 위해 string화 시킴
    temp[int(tp)]+=1 # 넣을땐 다시 int로 해서 temp에 넣음

for i in range(10): # 출력
  print(i,":",temp[i],"개")

2016/04/07 06:17

lcs901221

파이썬 3.5.1 64

for x in range(10):print('%d: %d'%(x,''.join(map(str, range(1, 1001))).count(str(x))))

또는

_ = list(print('%d: %d'%(i, l.count(str(i)))) for i in range(10) for l in [''.join(map(str, range(1, 1001)))])

C++

#include <iostream>
using namespace std;

int main(){
  string li[1000];
  int result[10];
  for(int x=1;x<=1000;x++)
    li[x-1] = to_string(x);
  for(int x=0;x<1000;x++){
    for(int y=0;y<li[x].length();y++){
        int index = li[x].at(y) - '0';
      result[index] += 1;
    }
  }
  for(int x=0;x<10;x++)
    cout << result[x] << endl;
    return 0;
}

자바

public class MyClass {
    public static void main(String[] args) {
        int target = 1000;
        int[] list = new int[target];
        int[] result = new int[10];
        for(int x = 0; x < list.length; x++){
            list[x] = x;
        }
        for(int x = 0; x < result.length; x++) {
            result[x] = 0;
        }
        for(int x = 1; x < list.length+1; x++){
            char[] c = (""+x).toCharArray();
            for(char j:c){
                result[Character.getNumericValue(j)] += 1;
            }
        }
        for(int i:result){
            System.out.println(i);
        }
    }
}

0: 192 1: 301 2: 300 3: 300 4: 300 5: 300 6: 300 7: 300 8: 300 9: 300

2016/04/11 23:15

Flair Sizz

+1 파이썬 소스는 봐도 무슨 의미인지 모르겠네요 ㅠㅠ 파이썬 공부중인데... - 타울, 2016/06/21 00:49
+1 두번째 풀이에 _ = 이것으로 None 리스트를 처리할 수 있네요^^ - 디디, 2016/10/18 17:41
for i in range(10):
    print "\t[ %s ] - %s개"%(i,''.join(map(str, range(1, 1001))).count(str(i)))

2017/05/18 14:20

jinyyo

C로 풀었습니다.

#include<stdio.h>

int main(void){
    int start, end, nam, mok;
    int i, k;
    int array[10]={0,1,2,3,4,5,6,7,8,9};    // 비교할 숫자들이 들어간 배열
    int check[10]={0,0,0,0,0,0,0,0,0,0};    // 비교 후에 count한 값이 들어갈 배열

    printf("두 숫자를 입력하시오.\n");
    scanf("%d", &start);
    scanf("%d", &end);

    for(i=start; i<end+1; i++){
        mok=i;
        while(mok>0){
            nam=mok%10;
                printf("%d  ", nam);
            for(k=0; k<10; k++){
                if(nam==array[k]){
                check[k]=check[k]+1;
                }
            }
            mok = mok/10;           
        }       
    }
    printf("\n");
    for(k=0; k<10; k++){
        if(check[k]!=0)
        printf("%d:%d개\t", k, check[k]);
    }
    printf("\n");   
}

2016/04/10 20:42

박주미

result = [0, 0, 0, 0, 0,  0, 0, 0, 0, 0]
for j in range(1, 1001):
    for x in str(j):
        result[int(x)] += 1

print(result)

2016/04/27 09:58

SanghoSeo

인트랑 스트링이랑 바꿔치는게 예술이네요 ㄷㄷ - 아울, 2020/05/05 08:02
    public static void main(String[] args) {

        int box[] = new int[10];

        for(int i=1; i <=1000;i++){
            box[i%10]++;
            if(i>=10) box[(i/10)%10]++;
            if(i>=100) box[(i/100)%10]++;
            if(i==1000) box[1]++;
        }
        System.out.println(Arrays.toString(box));

    }

답은 : [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

2017/06/11 20:23

kihyun lee

파이썬입니다. 원하는 숫자를 찾으면 딕셔너리의 값을 하나씩 올려서 갯수를 세는 방식입니다.

dic = {i:0 for i in range(0,10)}
for i in range(1,1001):
    for n in str(i):
        dic[int(n)]+=1
print(dic)

2018/07/25 18:23

김준영

멋지네요 - sjm, 2019/04/21 18:17

정답은 이렇습니다. 0: 192개, 1: 289개, 2: 300개, 3: 300개, 4: 300개, 5: 300개, 6: 300개, 7: 300개, 8: 300개, 9: 300개

    static int count[] = new int[10];
    public void countNumbers(int n){
        int num  = n % 10;
        count[num] +=1;
        while(n > 10){
            n = n / 10 ;
            count[n%10] += 1;
        }
    }

    public void count(int n, int m){
        for(int i = n ;  i<=m ;i++){
            countNumbers(i);

        }
        for(int i = 0 ; i < 10 ;i++){
            System.out.print(i + ": " + count[i] +"개, " );
        }

    }

2016/04/11 21:34

xeo

Java Lambda 작성

IntStream.rangeClosed(1, 1000).mapToObj(x->String.valueOf(x)).map(w->w.split("")).flatMap(Arrays::stream).collect(Collectors.groupingBy(java.util.function.Function.identity(), Collectors.counting())).forEach((k,v)->System.out.println(k+":"+v));

2016/04/25 14:36

하늘아빠

//javascript
var arr = [0,0,0,0,0,0,0,0,0,0];

for(var i=1; i<=1000; i++){
    var num = i;
    while (num > 0) {
        arr[num % 10] +=1;
      num = parseInt(num/10);
    }
}

console.log($.map( arr, function( val, key ) {return key+":"+val+"개"; }).join(", "));

2016/08/04 18:40

song ah-young

c로 해봤습니다

#include<stdio.h>

int main(void)
{
    int i, j;
    int arr[10] = { 0, };

    for (i = 1; i <= 1000; i++)
    {
        j = i;
        while (j != 0)
        {
            arr[j % 10]++;
            j /= 10;
        }
    }

    for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
    {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

2016/08/13 12:24

Choi Byeong Gyu

num_list =[]

for str_num in str(range(1,1001)):
    num_list.append(str_num)

for i in range(0,10):
    print i, ':', num_list.count(str(i))

2016/11/29 13:00

L JW

#include <stdio.h>
#pragma warning(disable:4996)
int main(void) {
    int from, to;
    int arr[10] = { 0 };
    scanf("%d %d", &from, &to);
    for (int i = from; i <= to; i++) {
        int k = i;
        while (k > 0) {
            arr[k % 10]++;
            k /= 10;
        }
    }
    for (int i = 0; i < 10; i++)
        printf("%d : %d \t", i, arr[i]);
}

2017/01/26 11:54

도야지

dic = {x:0 for x in range(10)}

for i in range(1,1001):
    for j in str(i):
        dic[int(j)] += 1

print(dic)

2017/06/24 21:56

a = {}
for x in range(1,1001):
    for y in str(x):
        if a.get(y) == None:
            a[int(y)] = 1
        else:
            a[int(y)] = a[y] + 1
print a.items()

Python입니다

2017/07/31 18:35

P.Y.Thon

a=[x for x in range(1,1001)]
n=0
while n<10:
    print('{0}: {1}'.format(n,str(a).count(str(n))))
    n=n+1

2017/11/01 17:59

강상욱

# 한글 처리 in Atom 1.21.1 + Anaconda(Python 3.6.3)
import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')

# 예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자
# 10 = 1, 0
# 11 = 1, 1
# 12 = 1, 2
# 13 = 1, 3
# 14 = 1, 4
# 15 = 1, 5
# 그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개

digit = [0 for i in range(10)]

for i in range(1, 1001):
    for x in str(i):
        digit[int(x)] += 1

for i in range(10):
    print(i, digit[i])

2017/11/01 19:10

Jace Alan

#include<stdio.h>

int main()
{
    int count[10] = { 0, }, i, tmp;

    for (i = 1; i < 1001; i++) {
        count[i % 10]++;
        if (i >= 10 && i < 100) {
            count[i / 10]++;
        }
        else if (i >= 100 && i < 1000) {
            count[i / 100]++;
            count[(i / 10) % 10]++;
        }
        else if (i >= 1000 && i < 10000) {
            count[i / 1000]++;
            count[(i / 100) % 10]++;
            count[(i / 10) % 10]++;
        }
    }

    for (i = 0; i < 10; i++)
    {
        printf("%d : %d\n", i, count[i]);
    }

    getchar();
}

2018/08/08 01:13

심준범

결과: {'0': 192, '1': 301, '2': 300, '3': 300, '4': 300, '5': 300, '6': 300, '7': 300, '8': 300, '9': 300}

# numDic = {}           
# for n in range(0,10):     # 초기 key, value 설정
#     numDic[str(n)] = 0    # 딕셔너리 변수에 key를 0~9로 설정, 각 키값에 대한 value(count)는 0으로 설정 
numDic = {str(n):0 for n in range(0,10)}    # 위의 3줄을 한줄로 변경
for i in range(1, 1001):    # 1~1000까지 차례로 소환
    numStr = str(i)         # 숫자를 한자리씩 쉽게 쪼개기 위하여 string으로 변경
    for j in numStr:        # 한자리씩 소환       
        numDic[j] += 1      # 해당 key의 value 값 1씩 누적
print(numDic)   # 결과 출력

2019/06/23 23:56

Hyebin Oh

int[] index = new int [10];
for(int i=1; i<=1000; i++) {

    char[] j = String.valueOf(i).toCharArray(); 

        for(char k : j) {
            int l = Character.getNumericValue(k);
            for(int n=0; n<10; n++) {
                if (l == n) {
                    index[n] += 1;
                }
            }
        }
    } // 계산부분

    for(int n=0; n<index.length; n++) {
        System.out.println(n+"의 개수 : "+index[n]);
    } // 출력부분

답 : 0의 개수 : 192, 1의 개수 : 301, 2의 개수 : 300, 3의 개수 : 300, 4의 개수 : 300, 5의 개수 : 300, 6의 개수 : 300, 7의 개수 : 300, 8의 개수 : 300, 9의 개수 : 300

2019/09/27 16:34

yeeun shim

a = { i:0 for i in range(0,10) }

for i in range(1, 1001):
    for k in str(i):
        a[int(k)] += 1

print(a)

2022/01/20 09:38

이승환

numstring = ""
for i in range(1, 1001) :
  numstring += str(i)
numlist = [k for k in numstring]
for j in range(0, 10) :
  print(numlist.count(str(j)))

2022/05/09 21:21

나유진

for i in range(0, 10):
    print("{} : {}개".format(i, str(list(range(1, 1001))).count(str(i))))

1부터 1000까지 쭉 나열하는 string만들어서 0부터 9까지 i가 반복하며 count하는 방식으로 풀었습니다.

2022/06/20 16:04

김정욱

alist = []
for ii in range(1, 1001):
    for i in str(ii):  # 이게 key포인트!
        alist.append(i)
for ii in range(10):
    print('{}은 {}개'.format(ii, alist.count(str(ii))))

2022/07/04 15:58

Tae Joo

뉴비가 python 2.7.10 으로 해봤어여

line = ''
line = "".join(map(lambda x: line+str(x), range(1,1001)))
for i in range(10):
        print "%d:%d"%(i,line.count(str(i)))

2016/04/08 15:43

Hwang Chul

Ruby

cnter = ->n { ([*1..n]*'').chars.reduce(Hash.new(0)) {|a,c| a[c]+=1; a} }

or

cnter = ->n { ('1'..n.to_s).each_with_object(Hash.new(0)) {|s,h| s.each_char{|c| h[c]+=1 } } }

Test

expect(cnter[5]).to eq({"1"=>1, "2"=>1, "3"=>1, "4"=>1, "5"=>1})
expect(cnter[1000]).to eq( {"1"=>301, "2"=>300, "3"=>300, "4"=>300, "5"=>300,
                            "6"=>300, "7"=>300, "8"=>300, "9"=>300, "0"=>192} )

2016/04/09 20:40

rk

keys = [0,1,2,3,4,5,6,7,8,9]

values = [0,0,0,0,0,0,0,0,0,0]

for i in range(1,1001):
    l = []
    l.append(str(i))
    for j in range(len(l[0])):
            for k in range(10):
                if int(l[0][j]) == k:
                    values[k] += 1
dic = dict(zip(keys, values))
print dic

{0: 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300}

풀이 쓰는 거 들여쓰기도 안 되고 어케 하는지 하나도 모르겠다 존나 빡치네 구제좀

2016/04/12 11:30

김 기수

파이썬3.5입니다.

def process(n):
    r = {}
    for x in str(n):
        r[x] = r.get(x, 0) + 1
    return r

result = dict()
for i in range(1, 1001):
    for k, v in process(i).items():
        result[k] = result.get(k, 0) + v
print("\n".join("{0}:{1}".format(*x) for x in sorted(result.items())))

2016/04/20 11:35

룰루랄라

자바로 풀어봄

int cnt[] = new int[10];
for(int i=1;i<=1000;i++)
      for(char ch : (i+"").toCharArray()) cnt[ch-'0']++;
for(int i=0;i<cnt.length;i++)
      System.out.println(i + " : " + cnt[i] + " " );

2016/04/20 18:33

김중운

result=[0]*10
for i in range(1,1001):
    a=str(i)
    for j in a:
        result[int(j)]+=1
print(result)

2016/04/20 21:24

Dr.Choi

python 2.7

s = ''.join(map(str, range(1,1001)))
for i in range(10):
    print i,s.count(`i`)

2016/04/22 19:21

상파

int arr[] = new int[10];
for(int i = a; i <= b; i++) {
    int tmp = i;
    do  {arr[tmp % 10]++;} while((tmp /= 10) != 0);
}
System.out.println(Arrays.toString(arr));

2016/04/25 14:15

조서환

파이썬으로 작성했습니다. (파이썬 초보자입니다.)

s = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for index in range(1,1001):
    str_number = str(index)
    int_size = len(str_number)
    for char_index in range(int_size):
        s[int(str_number[char_index])] = s[int(str_number[char_index])] + 1

for i in range(10):
    print "No of %d : %d" %(i, s[i])

2016/04/28 00:17

Coke



b=1 
a=0 
c=0 
d=0 
e=0

a1=0
a2=0
a3=0
a4=0
a5=0
a6=0
a7=0
a8=0
a9=0
a0=0

while d*1000+c*100+a*10+b<1001:

    if a==0  and d*1000+c*100+a*10+b>9:
        a0=a0+1
    elif a==1:
        a1=a1+1
    elif a==2:
        a2=a2+1
    elif a==3:
        a3=a3+1
    elif a==4:
        a4=a4+1
    elif a==5:
        a5=a5+1
    elif a==6:
        a6=a6+1
    elif a==7:
        a7=a7+1
    elif a==8:
        a8=a8+1
    elif a==9: 
        a9=a9+1



    if b==0:
        a0=a0+1
    elif b==1:
        a1=a1+1
    elif b==2:
        a2=a2+1
    elif b==3:
        a3=a3+1
    elif b==4:
        a4=a4+1
    elif b==5:
        a5=a5+1
    elif b==6:
        a6=a6+1
    elif b==7:
        a7=a7+1
    elif b==8:
        a8=a8+1
    elif b==9:
        a9=a9+1

    if c==0 and d*1000+c*100+a*10+b>100:
        a0=a0+1
    elif c==1:
        a1=a1+1
    elif c==2:
        a2=a2+1
    elif c==3:
        a3=a3+1
    elif c==4:
        a4=a4+1
    elif c==5:
        a5=a5+1
    elif c==6:
        a6=a6+1
    elif c==7:
        a7=a7+1
    elif c==8:
        a8=a8+1
    elif c==9:
        a9=a9+1


    if b==9:
        if a==9:
            a=0
            b=0
            c=c+1            
            if c==10:
                a=0
                b=0
                c=0
                d=d+1
        else:
            b=0
            a=a+1
    else:
        b=b+1
print("1:",a1,"2:", a2,"3:", a3,"4:", a4,"5:", a5,"6:", a6,"7:", a7,"8:", a8,"9:", a9,"0:", a0)



똥덩어리 투척하고 가서 죄송합니다. 배운지 1주일 쫌 넘어가네요 (이게 첫 언어에요) 다음부터는 튜플이라도 쓸게요

2016/04/28 15:42

이 지성

>>> from collections import Counter
>>> Counter("".join(map(lambda x: str(x), range(1,1001))))
Counter({'1': 301, '3': 300, '2': 300, '5': 300, '4': 300, '7': 300, '6': 300, '9': 300, '8': 300, '0': 192})

2016/05/02 21:40

Park Ohyoung

    @Test
    public void processing() {
        for(int i=1;i<=1000;i++) {
            call(i);
        }
        logger.debug("{}", counting);
    }

    private void call(Integer number) {
        if (number > 10) call(number / 10);
        counting[number%10]++;
    }

2016/05/04 18:58

Lee Brandon

e = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for a in range(0,10): #100
    for b in range(0, 10): #10
        for c in range(0, 10): #1
            multiply = (a * 100) + (b * 10) + c
            if not multiply == 0:
                for d in str(multiply):
                    e[int(d) ] += 1
for i in '1000':
    e[int(i)] += 1

print (e)
e = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for a in range(1,1001):
    for d in str(a):
        e[int(d) ] += 1

print (e)

2016/05/07 22:43

C13H12N4O2

    static int[] count = new int[10];
    public static void main(String[] args) {
        int cut, rest, Cut, CCut;
        for(int i=1;i<10;i++) {
            rest = i%10; 
            Count(rest);
        }
        for(int k=10;k<100;k++) {
            cut = k/10;
            rest = k%10;
            Count(cut);
            Count(rest);
        }
        for(int z=100;z<1000;z++) {
            Cut = z/100;
            cut = (z-(100*Cut))/10;
            rest = (z-(100*Cut))%10;
            Count(Cut);
            Count(cut);
            Count(rest);
        }
        for(int x=1000;x<1001;x++) {
            CCut = x/1000;
            Cut = (x-(1000*CCut))/100;
            cut = (x-(100*Cut))/10;
            rest = (x-(100*Cut))%10;
            Count(CCut);
            Count(Cut);
            Count(cut);
            Count(rest);
        }
        for(int j=0;j<count.length;j++) {
            System.out.println(count[j]);
        }
    }
    public static void Count(int num) {
        switch(num) {
            case 0: count[0] += 1; break;
            case 1: count[1] += 1; break;
            case 2: count[2] += 1; break;
            case 3: count[3] += 1; break;
            case 4: count[4] += 1; break;
            case 5: count[5] += 1; break;
            case 6: count[6] += 1; break;
            case 7: count[7] += 1; break;
            case 8: count[8] += 1; break;
            case 9: count[9] += 1; break;
        }
    }

2016/05/08 21:37

Frailos

#파이썬3.5.1
n = ''
ans = {}
for i in range(1,1001):
    n += str(i)
for i in range(0,10):
    ans[i] = n.count(str(i))

for i in ans:
    if ans[i] == 0:
        print('There\'re no',str(i)+'s in numbers.')
    else:
        print('There\'re',ans[i],str(i)+'s in numbers.')

2016/05/13 23:52

차우정

int arr[10] = {0,};

for(int num=1 ; num <= 999; num++)
{
     int temp1 = num/100;   // 백의 자리
     int temp2 = (num - temp1*100) / 10;   // 십의 자리
     int temp3 = num % 10;   // 일의 자리
     if(num >= 100)
          arr[temp1]++; arr[temp2]++; arr[temp3]++;
     else if(num < 100 && num >= 10)
          arr[temp2]++; arr[temp3]++;
     else
          arr[temp3]++;   
}

// 1000 에 대한 값
arr[0] = arr[0] + 3; 
arr[1] = arr[1]++;


네자리수는 1000 밖에 없어서 1000에 대한 값은 따로 했습니다.

2016/05/14 13:57

Kim Cheol Joong

파이썬 2.7 입니다

d = {}
for i in range(1,1000 + 1):
    i_t = tuple(str(i))
    i_l = list(i_t)
    for ii in i_t:
        try:
            d[ii] = d[ii] + 1
        except:
            d[ii] = 1
for i in range(0,9 + 1):
    print "%d : %d" %(i, d[str(i)])

2016/05/16 17:46

정민 허


        int min_input,max_input;
    int count[10] = {0,};

    int temp;

    bool mod=false;

    cout << "min input : ";
    cin >> min_input;

    cout << "max input : ";
    cin >> max_input;

    for (int i = min_input; i <= max_input; i++)
    {

        mod = false;

        temp = (i / 1000)%10;
        if(temp!=0)
        {
            count[temp]++;
            mod=true;
        }

        temp = (i / 100)%10;
        if (temp != 0 || mod == true)
        {
            count[temp]++;
            mod = true;
        }

        temp = (i / 10)%10;
        if (temp != 0 || mod == true)
        {
            count[temp]++;
            mod = true;
        }

        temp = i % 10;
        count[temp]++;

    }

    for (int j = 0; j < 10; j++) cout << j <<" : " << count[j] << endl;

2016/05/17 00:09

Cho Minho

파이썬3

total=[]
number=[0]*10
for num in range(1,1001):
    s=str(num)
    for i in s:
        total.append(i)
for i in total:
    for ii in range(10):
        if int(i)==ii:
            number[ii]+=1
for i in range(10):
    print(i,':',number[i])

2016/05/18 12:17

징짱더럽

php

$result = array(0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,9=>0);

for($i=1;$i<1001;$i++)
{
    $tmp = strval($i);
    $tmp_array = str_split($tmp);

    foreach($tmp_array as $key => $value)
    {
        $result[$value]++;
    }
}

foreach($result as $key => $count)
{
    echo $key." : ".$count."\n";
}
0 : 192
1 : 301
2 : 300
3 : 300
4 : 300
5 : 300
6 : 300
7 : 300
8 : 300
9 : 300

2016/05/18 22:07

김 원석

from collections import defaultdict
d = defaultdict(int)
for i in ''.join([str(i) for i in range(10, 16)]):
  d[i] += 1
print d

2016/05/19 14:35

choo dg

파이썬 3.5로 풀었습니다.

numbers = []

for num in range(1, 1001):
    for s in str(num):
        numbers.append(s)

for x in range(10):
    print('{}: {}'.format(x, numbers.count(str(x))))

2016/05/20 00:34

Analyticsstory

total = ""
for i in range(1, 1001):
    total = total + str(i)

for k in range(10):
    result = total.count('%d' % k)
    print("%d의 개수: %d" % (k, result))

Python 3.5으로 풀었습니다.

파이썬 배운지 일주일된 초보입니다.

굉장히 직관적으로 풀었습니다. 그냥 1부터 1000까지 다 문자로 바꾸고 그걸 total에 다 더해서 1~9까지 문자를 카운터 하는 방법으로 풀었습니다.

숫자가 커지면 메모리를 많이 쓰는 좋지않은 코드죠. 다른 분들의 소스를 보면서 많이 배워갑니다.

감사합니다.

2016/05/24 05:17

greatfarmer

Scanner scan=new Scanner(System.in);

    while(true){
    System.out.println("숫자 입력해봐.");
    int input=Integer.parseInt(scan.nextLine());



    int a=0;
    int b=0;
    int c=0;
    int d=0;

    //1의 자리.
    if(input<10 && input>=0){

        a=input;
        System.out.println("기존숫자:"+input+"결과:"+a);
        break;
    }
    //10의 자리
    else if(input>=10 && input<100){

        a=(input/10);
        b=(input-(input/10)*10);    
        System.out.println("기존숫자:"+input+"결과:"+a+","+b);
        break;

    }
    //100자리
    else if(input>=100 && input <1000){

        //첫 자리
        a=(input/100);
        //두번째
        b=((input-((input/100)*100))/10);
        //세번째
        c=input-(a*100)-(b*10);

        System.out.println("기존숫자:"+input+"결과:"+a+","+b+","+c);
        break;
    }
    //1000일때
    else if(input==1000){

        System.out.println("1000");
        break;
    }
    else{
        System.out.println("다시 입력하세요.");
        continue;

    }
    }

}

2016/05/26 13:23

정 성훈

#for 구문을 돌리기 위한 변수들
i = ""
j = ""
k = ""

#0부터 9까지 수를 카운팅 하기 위한 리스트
result= [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

#숫자를 문자열화 시킨 후 문자열 리스트를 위치별로 호출하여 0~9와 비교한 후
#일치하면 해당 리스트의 위치에 +1 카운팅.
for i in range(1, 1001):
    a = str(i)
    for j in range  (0, len(a)):
        for k in range (0, 10):
            if k == int(a[j]):
                result[k] = result[k] + 1



# 리스트 값을 출력 
for i in range(0, 10):
    print(i, '의 갯수 :', result[i], "개 입니다.")

2016/05/27 10:20

식섭

Java로 구현

import java.lang.Integer;
import java.lang.reflect.Array;
import java.nio.charset.StandardCharsets;

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

        for (int i = 1; i <= 1000; i++) {
            byte[] tempBytes = String.valueOf(i).getBytes(StandardCharsets.US_ASCII);

            for (int j = 0; j < Array.getLength(tempBytes); j++)
            {
                if ((tempBytes[j] >= 48) && (tempBytes[j] <= 57))
                    count[tempBytes[j] - 48]++;
                else
                    break;
            }
        }

        for (int e : count)
            System.out.print(e + " ");

        System.out.println();
    }
}

2016/06/04 14:05

손 량

C++ map 자료구조를 사용했습니다

#include <iostream> 
#include <cstdio> 
#include <algorithm> 
#include <map> 
using namespace std; 

int main(){ map<int,int> mp; for (int i = 10; i <= 15; i++){ int num = i;
while (num){ mp[num%10]++;
num /= 10; } } for (map<int,int>::iterator it = mp.begin(); it != mp.end(); it++){ printf("%d:%d\n",it->first,it->second); } return 0;
}

2016/06/04 15:21

iljimae

golang으로 구현

package main

import (
    "fmt"
    "strconv"
    "sort"
)

func main() {
    num1, num2 := 1, 1000
    tbl := make(map[rune]int)

    for i := num1; i <= num2; i++ {
        str := strconv.Itoa(int(i))
        for _, v := range(str) {
            tbl[v] += 1
        }
    }

    keys := make([]int, 0, len(tbl))
    for k, _ := range(tbl) {
        keys = append(keys, int(k))
    }

    sort.Ints(keys)

    for _, v := range(keys) {
        r := rune(v)
        fmt.Printf("%c %d\n", r, tbl[r])
    }
}

2016/06/06 23:20

uuuuuup

파이썬 2.7

counts=dict()
add=list()
a=list()

for k in range(1,1001):
    u=str(k)
    a.append(u)

for i in a:
    if len(i)==1:
        add.append(i)

    elif len(i)==2:
        add.append(i[0])
        add.append(i[1])
    elif len(i)==3:
        add.append(i[0])
        add.append(i[1])
        add.append(i[2])
    else:
        add.append(i[0])
        add.append(i[1])
        add.append(i[2])
        add.append(i[3])
for j in add:
    counts[j]=counts.get(j,0)+1

t=counts.items()
t.sort()
print t

2016/06/07 17:26

물방울

package main

import (
    "strconv"
    "fmt"
)

func main() {
    table := [10]int{}

    for i := 1; i <= 1000; i++ {
        s := strconv.Itoa(i)
        for _, v := range s {
            num := (int)(v - '0')
            table[num]++
        }
    }

    for i, v := range table {
        fmt.Printf("%d : %d개\n", i, v)
    }
}

2016/06/14 23:58

uuuuuup

# 1 ~ 1000에서 각 숫자의 갯수 구하기
def my_count(start, end): 
    keys = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    value = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for i in range(start, end + 1):
        string = str(i)
        for j in string:
            value[int(j)] += 1
    for i in range(10):
        print(i, ":", value[i], "개")
my_count(1, 1000)

0 : 192 개 1 : 301 개 2 : 300 개 3 : 300 개 4 : 300 개 5 : 300 개 6 : 300 개 7 : 300 개 8 : 300 개 9 : 300 개

2016/06/20 21:03

최기준

C++로 작성했습니다 카운트 하는 배열을 만들었고 나눠서 나온 값이 곧 배열의 첨자가 되도록 하여 카운트 하도록 작성하였습니다. 예 ) 535 / 100 = 5 이므로 counter[5] = counter[5]+1

#include <iostream>
using namespace std;

int main()
{
    int counter[10]={0,0,0,0,0,0,0,0,0,0}; //0,1,2,3,4,5,6,7,8,9

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

        int n = i;
        if(i>=1000)counter[n/1000]+=1;
        n=n%1000;

        if(i>=100)counter[n/100]+=1;
        n=n%100;

        if(i>=10) counter[n/10]+=1;
        counter[n%10]+=1;
    }

    for(int i=0; i<10; i++)
        cout << i << " : " <<counter[i] << endl;
}

0 : 192 1 : 301 2~9 까지 300이 출렵됩니다

2016/06/21 15:42

Kwon Doyun

답은 0 ==> 192 1 ==> 301 2 ==> 300 3 ==> 300 4 ==> 300 5 ==> 300 6 ==> 300 7 ==> 300 8 ==> 300 9 ==> 300

자바로 작성 하였습니다. 숫자 -> 문자 변환 -> char 로 잘라서 -> num 배열에 저장하였습니다.

    public static void main(String[] args){

        int num[] = new int[10];

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

            Integer tempNum = i;
            String charNum[] = tempNum.toString().split("");

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

                System.out.print( charNum[j] + "  " );
                num[ Integer.parseInt(charNum[j])]++;
            }
                System.out.println("");
        }

        for(int i=0; i<num.length; i++){

            System.out.println("번호 :: ==> " + i + "  " + "개수 :: ==> " + num[i]  );
        }

    }

2016/06/23 17:55

황 정석

# Python

s=""
for i in range(1000):
    s = s + str(i+1)
print("0: %d개\n1: %d개\n2: %d개\n3: %d개\n4: %d개\n5: %d개\n6: %d개\n7: %d개\n8: %d개\n9: %d개"
      %(s.count('0'),s.count('1'),s.count('2'),s.count('3'),s.count('4'),s.count('5'),
        s.count('6'),s.count('7'),s.count('8'),s.count('9'),))

2016/06/24 13:53

Kim Dalwoo

GCC

j;i=1001;a[9];main(){for(;i;)j?a[j%10]++,j/=10:(j=--i);for(;i<10;)printf("%d : %d\n",i++,a[i]);}

2016/06/25 11:13

Lotion

array = [0,0,0,0,0,0,0,0,0,0]

for n in range(1, 1001) : 
    while n > 0 :
        array[n % 10] += 1
        n = n // 10

for i in range(0, 10) :     
    print ( array[i] )


2016/06/26 22:23

안 동환

  3 int main()
  4 {
  5     int i, temp = 0;
  6     int check[10] = { 0, };
  7 
  8     for(int i = 10; i <= 15; i++)
  9     {
 10         temp = i;
 11         while(temp / 10 != 0)
 12         {
 13             check[temp % 10]++;
 14             temp = temp / 10;
 15         }
 16         check[temp]++;
 17     }
 18 
 19     for(int i = 0; i < 10; i++)
 20     {
 21         printf("%d : %d개 \n", i, check[i]);
 22     }
 23 
 24     return 0;
 25 }

C로 짰습니다.

결과 0 : 192개 1 : 301개 2 : 300개 3 : 300개 4 : 300개 5 : 300개 6 : 300개 7 : 300개 8 : 300개 9 : 300개

2016/07/01 01:22

유원준

a=[0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    for j in str(i):
        a[int(j)]+=1

for i in range(10):
    print("%d:%d개"%(i,a[i]),end=' ')

2016/07/01 06:42

이 준오

class gop {
    int x1 = 1;
    int x2;
    int x3;
    int result;

    public gop() {}

    public gop(int x2, int x3) {
        this.x2 = x2;
        this.x3 = x3;
    }
    public gop(int x1, int x2, int x3) {
        this.x1 = x1;
        this.x2 = x2;
        this.x3 = x3;
    }

    public int method() {
        result = x1 * x2 * x3;
        return result;
    }
}


public class question1 { 
    public static void main(String[] args) {
        int result = 0;
        for (int i = 0; i < 10; i++) {
            for (int j = 1; j < 10; j++) {
                for (int k = 1; k < 10; k++) {
                    if (i <= 1) {
                        gop g = new gop(j,k);
                        result += g.method();
                    } else {
                        gop g = new gop(i, j, k);
                        result += g.method();
                    }

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

}

자바로 생성자를 이용하여 계산했습니다.

2016/07/01 19:43

재범 소

temp = [0,0,0,0,0,0,0,0,0,0]

for num in range(1,1001):
    while num > 0:
        index = int(num%10)
        temp[index] += 1
        num //= 10

for i in range(0,10):
    print(temp[i])

2016/07/04 16:14

김종국

자바 컬렉션을 사용하여 풀어봤습니다 ㅠㅠ

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class 각숫자의개수구하기1에서1000 {

    public static void main(String[] args) {

        Map<Character, Integer> numberMap = new LinkedHashMap<Character, Integer>();
        for(int start = 1; start <= 1000; start++){

            String numStr = String.valueOf(start);  // 문자열로 치환.

            for(int sIdx=0; sIdx<numStr.length(); sIdx++) {
                if(numberMap.get(numStr.charAt(sIdx)) == null) {
                    numberMap.put(numStr.charAt(sIdx), 1);
                } else {
                    int value = numberMap.get(numStr.charAt(sIdx)) + 1;
                    numberMap.put(numStr.charAt(sIdx), value);
                }
            }
        }

        Set<Character> set = numberMap.keySet();
        Iterator<Character> it = set.iterator();

        while(it.hasNext()) {
            char key = it.next();
            System.out.println(key + " : " + numberMap.get(key));
        }
    }

}

2016/07/06 13:43

강승윤

Python

list = []
for k in range(0, 10):
    list.append(0)

def count(n):
    s=str(n)
    for i in range(len(s)):
        a=s[i]
        b=int(a)
        list[b]+=1

for i in range(1,1001):
    count(i)

for i in range(0,10):
    print("%d 갯수: %d" % (i,list[i]))


2016/07/07 02:34

왈왈

#include<stdio.h>
void main() 
{ 
     int arr[10] = {0,0,0,0,0,0,0,0,0,0}; 
     int i = 1, a, integer = 0, b; 
     printf("숫자를 입력하세요 : "); 
     scanf("%d", &a); 
     for(i ; i < a; i++) { 
     b = i ; 
          while(b != 0 ){ 
               integer = b%10; 
               b = b / 10; 
               arr[integer] += 1; 
          } 
         } 
     for( i =0 ; i<10; i++) 
          printf("%d = %d \n ", i, arr[i]); 
}

2016/07/08 13:38

양 준모

package 코딩도장;

public class Q1 {

    public static void main(String[] args) {

        String abc = "";        
        for(int i=1;i<=1000;i++)
        {
            abc = abc+i;
        }       
        String Arr[] = abc.split("");
        int intArr[] = new int[10];

        for(int i = 0; i < Arr.length;i++)
        {
            if(Arr[i].equals("0"))
            {
                intArr[0]++;
            }
            else if(Arr[i].equals("1"))
            {
                intArr[1]++;
            }
            else if(Arr[i].equals("2"))
            {
                intArr[2]++;
            }
            else if(Arr[i].equals("3"))
            {
                intArr[3]++;
            }
            else if(Arr[i].equals("4"))
            {
                intArr[4]++;
            }
            else if(Arr[i].equals("5"))
            {
                intArr[5]++;
            }       
            else if(Arr[i].equals("6"))
            {
                intArr[6]++;
            }           
            else if(Arr[i].equals("7"))
            {
                intArr[7]++;
            }           
            else if(Arr[i].equals("8"))
            {
                intArr[8]++;
            }           
            else if(Arr[i].equals("9"))
            {
                intArr[9]++;
            }           

        }

        for(int i=0;i<intArr.length;i++)
        {
            System.out.println(i + " : " + intArr[i]);
        }

    }

}

2016/07/08 17:20

서동빈

JAVA

// 1~1000에서 각 숫자의 개수 구하기
public class CountNumbers {
    public static void main(String args[]){
        int[] num = new int[10];
        for (int i=1; i<=1000; i++){
            if(i/10==0){
                num[i]++;
            }
            else if(i/100==0){
                num[i/10]++;
                num[i-(i/10)*10]++;
            }
            else if(i/1000==0){
                num[i/100]++;
                num[(i/10)-(i/100)*10]++;
                num[i-(i/10)*10]++;
            }
            else{
                num[0] = num[0] + 3;
                num[1] = num[1] + 1;
            }
        }
        for (int k=0; k<=9; k++){
            System.out.println(k+"의 개수는 "+num[k]);
        }
    }
}

2016/07/10 02:23

자바를자바라

#include <stdio.h>
int main()
{
  int arr[10] = {0, };
  int i, num;

  for(i=1; i<1001; i++)
  {
    num = i;
    while(num)
    {
      arr[num % 10]++;
      num /= 10;
    }
  }

  // 출력
  for(i=0; i<10; i++)
  {
    printf("%d : %d 개 \n", i, arr[i]);
  }

  return 0;
}

2016/07/11 16:28

이진웅

alist=[]
for i in range(1, 1001):
    a=str(i)
    for k in range(0, len(a)):
        alist.append(a[k])

print(alist.count('0'))
print(alist.count('1'))
print(alist.count('2'))
print(alist.count('3'))
print(alist.count('4'))
print(alist.count('5'))
print(alist.count('6'))
print(alist.count('7'))
print(alist.count('8'))
print(alist.count('9'))

2016/07/14 23:04

최승호

C로 작성 했습니다.

#include <stdio.h>

void mod(int i);


int main(void)
{
    int z=0;
    int i;
    int count[10] = {0};
    printf("숫자를 입력해주세요 1~1000\n");
    scanf_s("%d", &i);
    mod(i); // mod함수 콜
    return 0;
}

    void mod(int i)
    {

        if (i == 0) // i가 0이면 종료
            return;

        int count[10] = { 0 }; // 0~9까지의 값을 추가하기위한 count배열 선언 
        int a=0; 
        int z=0;
        int temp; // i의 값을 저장할 변수
        for (i; i > 0; i--) // 입력받은 i를 1씩 감소시킴
        {
            temp = i; // i값을 temp에 저장

            while (temp != 0)
            {
                a = temp % 10; // temp를 모드연산하여 자릿수를 떼어내 a에 저장
                count[a] += 1; // 떼어낸값의 배열인덱스에 1씩 추가
                temp = temp / 10; // temp를 나눈 수의 몫을 temp에 저장하고 다시 실행
            }
        }

        for (z = 0; z < 10; z++) // 배열의 인덱스에 들어있는 값들을 출력
        {
            printf("%d의 개수는 %d개\n", z, count[z]);

        }

    }

2016/07/15 10:39

또뺏음

int count[] = new int[10];//0~9 카운트 셈을위한    배열
        for (int i = 1; i < 1001; i++) {
                count[i%10]++;//일의자리 추출
                if (i>=10) 
                    count[i/10%10]++;//십의자리 추출
                if (i>=100) 
                    count[i/100%10]++;//백의자리 추출
                if (i==1000) 
                    count[i/1000%10]++;//천의자리 추출
            }
            for(int n : count)//출력
            {
                System.out.print(n+", ");
            }

2016/07/15 13:57

Oh Tae Gyeoung

Python3.4 입니다.

num = [0,0,0,0,0,0,0,0,0,0]

for i in range(1,1001):
    for j in range(10):
        num[j] = num[j] + str(i).count(str(j))


print (list(enumerate(num)))

결과는

pi@raspberrypi:~ $ python3 countnum.py

[(0, 192), (1, 301), (2, 300), (3, 300), (4, 300), (5, 300), (6, 300), (7, 300), (8, 300), (9, 300)]

2016/07/20 03:55

예강효빠

재귀로 각 자리수를 구해서 배열에 넣고 올렸습니다.

#include <stdio.h>
int arr[10] = {};
void get(int i);

int main(void)
{
    int total = 0;
    int i;
    for (i = 1; i <= 1000; i++)
    {
        get(i);
    }
    for (i = 0; i < 10; i++)
    {
        printf("%d : %d 개\n", i, arr[i]);
    }
}

void get(int i)
{
    if (i < 10)
        arr[i]++;
    else
    {
        arr[i % 10]++;
        get(i / 10);
    }
}

2016/07/20 13:43

유한길

JAVA public static void main(String[] args) { // 1~1000까지 각자리의 갯수

    int arr[] = new int[10];
    for (int i = 1; i < 1001; i++) {

        arr[i % 10]++;
        if (i >= 10) {
            arr[i / 10 % 10]++;

            if (i >= 100) {
                arr[i / 100 % 10]++;
                if (i >= 1000) {
                    arr[i / 1000]++;
                }
            }
        }
    }

    for (int j = 0; j < 10; j++) {
        System.out.println(j + "\t" + arr[j]);
    }

2016/07/25 17:38

김치영

c++로 풀었습니다.

#include <iostream>

using namespace std;

int main(){
    int start, end;
    int result[10]={0,0,0,0,0,0,0,0,0,0};
    int num=0, num2=0;

    cin >> start;
    cin >> end;

    for(int i=start ; i<=end ; i++){    
        num = i % 10;
        result[num]++;  
        num = i/10;
        while(num>0){
            num2 = num%10;
            result[num2]++;
            num = num/10;
        }
    }
    for(int i=0; i<10 ;i++){
        if(result[i]!=0)
            cout << i << ":" << result[i] << "개 ";
    } 
    cout << endl;
    return 0;
}

2016/07/25 22:49

young

def count_i(n):
    count = 0
    i = ""
    for i2 in range(1,1001):
        i = i + str(i2)
    for i3 in i:
        if i3 == n:
            count = count + 1
    print(count)

count_i('n')

지금까지 배운 거로 최대한 쥐어 짜내서 풀어봤습니다 ㅠㅠ 맞는 방법인지는 모르겠네요.. 정말 초보자라 한 이틀 고민했습니다..

2016/07/27 18:52

정 대훈

b=int(input("Start :"))
c=int(input("End :"))
a=""
for i in range(b,c):
    a+=" ".join(str(i))
for j in range(10):
    print("%d = %s"%(j,a.count(str(j))))

Python 3.5.2

2016/07/27 20:29

Zee

sp=[0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    s=str(i)
    l=len(s)
    for j in range(0,l):
        sp[int(s[j])]+=1

print "0:%s 1:%s 2:%s 3:%s 4:%s 5:%s 6:%s 7:%s 8:%s 9:%s" %(sp[0],sp[1],sp[2],sp[3],sp[4],sp[5],sp[6],sp[7],sp[8],sp[9])

간단한 문제를 푸느라 2시간씩이나 고민했네요;; 아직 갈길이 머나 봅니다..

2016/08/01 16:46

Jeon Hyun Jong

이제 막 코딩시작한 1년차 늅늅입니다. 최근 자바를 연습하면서 풀어봤습니다.

public static int numberCount[];

    public static void main(String args[])
    {
        numberCount = new int[10];
        CountNumber(0, 15);
    }

    private static void CountNumber(int countStart, int countEnd)
    {
        for(int i = countStart; i < countEnd; i++)
        {
            String numStr = Integer.toString(i);

            for(int j = 0; j < numStr.length(); j++)
            {
                String s = String.valueOf(numStr.charAt(j));
                int tempInt = Integer.valueOf(s);

                numberCount[tempInt]++;
            }
        }

        for(int i = 0; i < numberCount.length; i++)
        {
            String result = Integer.toString(numberCount[i]); 
            System.out.println(i + "의 갯수는 " + result + "\n");
        }
    }

2016/08/02 14:31

여우와향신료

def count_number(start,end):
    dic = {0:0,1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0,9:0}
    for i in range(start,end+1):
        for number in str(i):
            a= int(number)
            dic[a] += 1
    return dic

print count_number(1,1000)

2016/08/02 20:18

kim SeongHyeon

count_arr = [0,0,0,0,0,0,0,0,0,0]

def count_each_number(seed):
    for i in range(1, seed):    
        divide_number(i)

def divide_number(num):
    count_arr[num % 10]+=1
    if num / 10:
        divide_number(num / 10)

count_each_number(1001)

for j in range(10):
    print("%d:%d" % (j,count_arr[j]))

2016/08/08 23:20

정 우순

package codingdojang;

import java.util.Scanner;

// 1~1000까지 각숫자의 개수 구하기
class num{
    Scanner sc;
    int n;
    int[] ki = new int[10];
    num(){
        sc = new Scanner(System.in);
        System.out.print("숫자입력  :");
        n = sc.nextInt();
        for(int i = 0 ;i<10;i++){
            ki[i] = 0;
        }
    }
    public void check(){
        for(int i = 1; i<=n;i++){
            if(i<10){
                ki[i%10]++;
            }
            else if(i<100){
                ki[i%10]++;
                ki[i/10%10]++;
            }
            else if(i<1000){
                ki[i%10]++;
                ki[i/10%10]++;
                ki[i/100%10]++;
            }
            else if(i<10000){
                ki[i%10]++;
                ki[i/10%10]++;
                ki[i/100%10]++;
                ki[i/1000%10]++;
            }
        }
    }
    public void disp(){
        for(int i=0;i<10;i++){
            System.out.println(i+" : "+ki[i]);
        }
    }
}
public class lv1_01 {
    public static void main(String[] args) { 
        num n = new num();
        n.check();
        n.disp();
    }
}

2016/08/10 20:23

김준호

dic={0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
for i in range(1,1001):
    for j  in str(i):
        add=int(j)
        dic[add]=dic[add]+1
for i in range(0,10):
    print('%d:%d' %(i,dic[i]))

python으로 작성.

2016/08/12 13:41

impri

  • C 로 작성해 보았습니다.
/* 2016.08.15.Mon

    1 ~ 1000 에서 각 숫자의 개수 구하기

*/
#include <stdio.h>

#define MAX 1001

int main(void)
{
#ifdef MY_ANSWER
    int i, j = 0;
    int temp;

    int arr[10] = {0, };

    for (i = 1; i < MAX; i++) {
        if (i < 10) {
            temp = i; arr[temp]++;
        }
        else if (i < 100) {
            temp = i / 10; arr[temp]++;
            temp = i % 10; arr[temp]++;
        }
        else if (i < 1000) {
            temp = i / 100; arr[temp]++;
            temp = i % 100; temp = temp / 10; arr[temp]++;
            temp = i % 10; arr[temp]++;
        }
        else if (i < 10000) {
            temp = i / 1000; arr[temp]++;
            temp = i % 1000; temp = temp / 100; arr[temp]++;
            temp = i % 100; temp = temp / 10; arr[temp]++;
            temp = i % 10; arr[temp]++;
        }
    }

    printf("===== print out array =====\n");

    for (j = 0; j < 10; j++) 
        printf("arr[%d] = %d\n", j, arr[j]);
#elif OTHER_ANSWER
    printf("===== dummy =====\n");
#endif

    return 0;
}

2016/08/15 15:07

WJ

머리로 풀기

우선 000~999로 생각해보면, 3000개의 숫자가 있고 여기에 0부터 9까지 모두 고루 분포하니까 2부터 9까지는 일단 반드시 300개가 있음을 안다.
이제 0과 1의 개수를 센다.
1000에서 1이 하나 더 들어가니 1은 301개가 있다. 이제 의미 없이 세어진 0을 제거해준다.
한 자리 자연수가 총 9개, 두 자리 자연수가 총 90개이니 의미 없는 0은 총 9*2+90=108개이다. (1000에서의 0 3개는 000에서 세어짐)
따라서 0은 192개, 1은 301개, 나머지 숫자는 모두 300개.

Python 3

p = "".join(map(str, range(1, 1001)))
for x in range(10):
        print("{0}: {1}개".format(x, p.count(str(x))))

2016/08/15 21:13

Kim

count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
n = input("nums >> ") //입력 횟수

for i in range(n):
    num = input("input num >> ") //숫자 입력
    for j in str(num): //입력된 숫자를 str형으로 형바꿈
        count[int(j)]+=1 //한자리씩 가져와 int형으로 형바꿈해 해당 자리에 +1

for i in range(10):
    print i, ': ', count[i] //결과 출력

2016/08/19 03:40

kissme123

Python 2.7

temp = ""

for n in range(1, 1001):
    tp = str(n)
    temp += tp

for i in range(0, 10):
    count = 0
    i = str(i)
    for j in temp:
        if i == j:
            count += 1
    print "%s: %d" %(i, count)

2016/08/21 16:28

빠리공원

public void CountOneToThousand()
        {
            int cnt0 = 0;
            int cnt1 = 0;
            int cnt2 = 0;
            int cnt3 = 0;
            int cnt4 = 0;
            int cnt5 = 0;
            int cnt6 = 0;
            int cnt7 = 0;
            int cnt8 = 0;
            int cnt9 = 0;

            for(int i = 1;i <= 1000; i++)
            {
                string Num = Convert.ToString(i);
                foreach(char num in Num)
                {
                    if (num == '0')
                        cnt0++;
                    if (num == '1')
                        cnt1++;
                    if (num == '2')
                        cnt2++;
                    if (num == '3')
                        cnt3++;
                    if (num == '4')
                        cnt4++;
                    if (num == '5')
                        cnt5++;
                    if (num == '6')
                        cnt6++;
                    if (num == '7')
                        cnt7++;
                    if (num == '8')
                        cnt8++;
                    if (num == '9')
                        cnt9++;

                }


            }
            Console.WriteLine(cnt0);
            Console.WriteLine(cnt1);
            Console.WriteLine(cnt2);
            Console.WriteLine(cnt3);
            Console.WriteLine(cnt4);

            Console.WriteLine(cnt5);
            Console.WriteLine(cnt6);
            Console.WriteLine(cnt7);
            Console.WriteLine(cnt8);
            Console.WriteLine(cnt9);


        }

O/P : (0부터 9까지 순서대로) 192 301 300 300 300 300 300 300 300 300

그나저나 코딩을 오랜만에 해봐서 코드가 쓸데없이 기네요 ㅋㅋ

2016/08/21 20:43

이규민

#include <iostream>
#include <string>

const int SIZE      = 10;
const int START     = 1;
const int END       = 1000;

void calculateDigit(int result[], int& val);

int main(int argc, const char * argv[]) {
    // insert code here...
    int result[SIZE] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    for(int i = START; i <= END; i++)
    {
        calculateDigit(result, i);
    }

    for (int i = 0; i < SIZE; i++)
    {
        std::cout << i << " : " << result[i] << std::endl;
    }

    return 0;
}

void calculateDigit(int result[], int& val) {
    std::string str = std::to_string(val);
    for (int i = 0; i < str.length(); i++)
    {
        const char digit = str[i];
        auto index = std::atoi(&digit);
        result[index]++;
    }
}

0 : 192 1 : 301 2 : 300 3 : 300 4 : 300 5 : 300 6 : 300 7 : 300 8 : 300 9 : 300

2016/08/22 01:13

정 태석

i=1 result='' while i<=1000: result=result+str(i) i=i+1

i=0 while i<10: print result.count(str(i)) i=i+1

2016/08/22 18:12

Jung Ki Hyun

python 2.7 Dic={}


for i in range(1,1001): for j in str(i): if j not in Dic.keys(): Dic[j] = 1 else: Dic[j]+=1 print Dic

2016/08/23 17:11

leye195

dic = {'0':0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0}

def CountUsedNaturalNumber(start, end):

    for i in range(start,end):
        for j in str(i):
            dic[j] += 1
    return dic



def CountUsedNaturalNumber2(start, end):

    a = [0,0,0,0,0,0,0,0,0,0]
    print(a)
    for i in range(start,end):
        j = i
        #print(j)        
        while j != 0:
            #print(int(j%10))
            a[int(j%10)] += 1
            j = int(j/10)
    return a


print(CountUsedNaturalNumber(1,1001))
print(CountUsedNaturalNumber2(1,1001))

2016/08/26 07:48

Kim Sean

include

int main(void){ int arr[10]={0,}; int i, j, len,temp;

for( i=1 ; i<=1000 ; i++ ){
    for( temp=i, len=1 ; temp/10!=0 ; len++, temp /= 10);
    for( j=0, temp=i ; j<len ; j++ ){
        arr[temp%10]++;
        temp /= 10;
    }
}

for( i=0 ; i<10 ; i++ ) printf("%d : %d\n", i, arr[i]);

}

2016/08/30 10:01

kawa1lg1rl

a = [0,0,0,0,0,0,0,0,0,0]
for number in range(10,16) :
        strNumber = str(number)
        splited1 = strNumber[0]
        splited2 = strNumber[1]

        a[int(splited1)] += 1
        a[int(splited2)] += 1

print(a)

2016/08/30 14:39

박창석

C언어
#include <stdio.h>

int main()
{
    int arr[10] = { 0, };
    int a, b, c, d;
    for (int i = 1; i <= 1000; i++)
        if (i < 10)
        {
            a = i % 10;
            for (int j = 0; j < 10; j++)
                if (a == j)
                    arr[j] += 1;
        }
        else if (i < 100)
        {
            a = i / 10;
            b = i % 10;
            for (int j = 0; j < 10; j++)
                if (a == j)
                    arr[j] += 1;
            for (int j = 0; j < 10; j++)
                if (b == j)
                    arr[j] += 1;
        }
        else if (i < 1000)
        {
            a = i / 100;
            b = i % 10;
            c = (i / 10) % 10;
            for (int j = 0; j < 10; j++)
                if (a == j)
                    arr[j] += 1;
            for (int j = 0; j < 10; j++)
                if (b == j)
                    arr[j] += 1;
            for (int j = 0; j < 10; j++)
                if (c == j)
                    arr[j] += 1;
        }
        else
        {
            a = i / 1000;
            b = i % 10;
            c = (i / 100) % 10;
            d = (i / 10) % 10;
            for (int j = 0; j < 10; j++)
                if (a == j)
                    arr[j] += 1;
            for (int j = 0; j < 10; j++)
                if (b == j)
                    arr[j] += 1;
            for (int j = 0; j < 10; j++)
                if (c == j)
                    arr[j] += 1;
            for (int j = 0; j < 10; j++)
                if (d == j)
                    arr[j] += 1;
        }
    for (int i = 0; i < 10; i++)
        printf("%d의 개수 : %d 개\n", i, arr[i]);

    return 0;
}

2016/08/30 19:01

GoldGD

result = [0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    text = str(i)
    for j in text:
        result[int(j)]+=1

for i in range(0,10):
    print(i ,":", result[i])

1번

2016/08/31 15:31

v제천대성v

import java.util.Scanner;

public class main {
    // 1~1000에서 각 숫자의 개수 구하기
    public static void main(String[] args) {
        // [0]~[9] 카운트 할 자리 배열
        int[] count = new int[10];

        // 숫자 2개 입력 받기
        Scanner scanner = new Scanner(System.in);
        System.out.println("1~1000 사이의 수를 입력하세요");
        while (true) {
            System.out.print("어디부터:");
            int input1 = scanner.nextInt();
            System.out.print("어디까지:");
            int input2 = scanner.nextInt();

            // 1~1000에 벗어나는 입력 거르기
            if (input1 > 0 && input1 < 1001 && input2 > 0 && input2 < 1001) {
                // 입력한 수(input1) ~ 입력한 수(input2)까지 반복
                for (int num = input1; num <= input2; num++) {
                    if (num < 10) {
                        count[num % 10]++;
                    } else if (num < 100) {
                        count[num % 10]++;
                        count[num / 10 % 10]++;
                    } else if (num < 1000) {
                        count[num % 10]++;
                        count[num / 10 % 10]++;
                        count[num / 100 % 10]++;
                    } else {
                        count[num % 10]++;
                        count[num / 10 % 10]++;
                        count[num / 100 % 10]++;
                        count[num / 1000 % 10]++;
                    }
                }
                // 배열 [0]~[9]까지 출력
                for (int i = 0; i < 10; i++) {
                    System.out.printf("%d : %d개\n", i, count[i]);
                }
                return;
            } else {
                System.out.println("1~1000 사이의 수를 다시 입력하세요");
            }
        }
    }

}

2016/08/31 16:53

JAVVVVVVA

python으로 풀었습니다.

a=[0,0,0,0,0,0,0,0,0,0]
for x in range(1, 1001):
    for n in str(x):
        a[int(n)]+=1
for x in range(10):
    print("%d:%d개"%(x,a[x]))

2016/09/02 18:14

정석철

python 2.7.12

from collections import Counter 
c = Counter()
for n in range(1, 1001) : c += Counter(str(n))
print sorted(c.items())

result

[('0', 192), ('1', 301), ('2', 300), ('3', 300), ('4', 300), ('5', 300), ('6', 300), ('7', 300), ('8', 300), ('9', 300)]

2016/09/03 15:33

happygrammer

/**
 * 
 */
package Lv1;

/**
 * 1~1000에서 각 숫자의 개수 구하기

    예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자

    10 = 1, 0
    11 = 1, 1
    12 = 1, 2
    13 = 1, 3
    14 = 1, 4
    15 = 1, 5
    그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개

 * @author Admin
 *
 */
public class Example1 {
    public static void main(String[] args) {
        int[] count = new int[10];
        for (int i = 1; i <= 1000; i++) {
            String num = String.valueOf(i);
            for (int j = 0; j < num.length(); j++) {
                int n = ((int)num.charAt(j)) - 48;
                count[n] = ++count[n]; 
            }
        }

        for (int i = 0; i < count.length; i++) {
            System.out.println(i + " : " + count[i]);
        }
    }
}

2016/09/06 12:09

양 충현

자바

package study;

import java.util.Arrays;

public class study {

    public static void main(String[] args) {
        int cnt[] = new int[10];
        int temp;
        Arrays.fill(cnt, 0);
        for (int i = 1; i < 1001; i++) {
            for(int j=i; j>0; j/=10){
                temp = j % 10;
                if(temp!=0){
                    cnt[temp]++;
                }else if (i / 10 > 0) {
                    cnt[temp]++;
                }
            }
        }
        for(int i=0; i<10; i++){
            System.out.println(i + " : " + cnt[i] + "개");
        }
    }
}

2016/09/08 18:01

JD

#include <stdio.h>

#define START 10
#define END 15

int main(){

    int a[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    int n = 0;
    for(int i = START; i <= END; i++) {
        n = i;
        if(n == 0){
            a[0]++;
        }
        while(n > 0) {
            a[n % 10]++;
            n /= 10;
        }
    }

    for(int i = 0; i < 10; i++) {
        if(a[i] > 0) {
            printf("%d:%dEA, ", i, a[i]);
        }
    }
}

2016/09/15 12:44

이 종성

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

void numcount(int);

int main(void) {
    int num;
    puts("숫자를 입력하시오 : ");
    scanf_s("%d", &num);

    numcount(num);
    system("pause");
    return 0;
}
void numcount(int num) {
    int p;
    int numct[10] = { 0, };

    for (int i = 1; i <= num; i++) {
        p = i;
        numct[p%10]++;
        while (p > 10) {
            p /= 10;
            numct[p%10]++;
        }
    }
    for (int i = 0; i < 10; i++) {
        printf("%d = %d개\n", i, numct[i]);
    }
}

2016/09/20 11:01

개허접

a=[0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    for j in str(i):
        a[int(j)]+=1

for i in range(10):
    print("%d:%d개"%(i,a[i]),end=' ')

2016/09/21 15:42

머얼씨

#include <iostream>
using namespace std;
int main(void)
{
    int i;  
    int number;
    int count[10];
    for(i=1;i<1001;i++)
    {
        count[i] = 0;
    }
    for(i=10;i<16;i++)
    {
        number = i;
        while(number > 0)
        {
            count[number%10] += 1;
            number /= 10;
        }
    }
    for(i=0;i<10;i++)
    {
        cout<<"count of "<<i<<": "<<count[i]<<"\n";
    }
    return 0;
}

2016/09/26 00:39

취미로재미로

source = ""
for x in range(1,1001):
    source = source + str(x)
for y in range(10):
    print "Number of %d %d" %(y, source.count(str(y)))

Number of 0 192 Number of 1 301 Number of 2 300 Number of 3 300 Number of 4 300 Number of 5 300 Number of 6 300 Number of 7 300 Number of 8 300 Number of 9 300

2016/09/28 17:13

Amadeus.J

Python 3. 5. 2 사용.

digitlist = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for n in range(1, 1001):
    d = n // 1000
    c = (n % 1000) //100
    b = (n % 100) // 10
    a = n % 10
    if d == 0:
        digitlist[0] -= 1
        if c == 0:
            digitlist[0] -= 1
            if b == 0:
                digitlist[0] -= 1
    digitlist[a] += 1
    digitlist[b] += 1
    digitlist[c] += 1
    digitlist[d] += 1
print(digitlist)

처음 하는 거라 좀 미숙합니다 ^^;;
참고로 [192, 301, 300, 300, 300, 300, 300, 300, 300, 300] 이런 식으로 출력됩니다.

2016/10/02 18:00

C295HB

#include <vector>
#include <map>
#include <string>
#include <iostream>

typedef std::map<int, int> ResultMap;
typedef std::vector<int> InputVector;
void countNumbers1(const InputVector& input, ResultMap& output){
    for (InputVector::const_iterator& num_iter=input.begin(); num_iter != input.end();num_iter++){
        std::string num_str = std::to_string(*num_iter);
        for (std::string::const_iterator c = num_str.begin(); c != num_str.end(); c++){
            int digit = *c - '0';
            ResultMap::iterator iter = output.find(digit);
            if (iter == output.end()){
                output[digit] = 1;
            }
            else{
                iter->second++;
            }
        }
    }
}

void showResult(const ResultMap& result){
    //
    /*for (const auto &ele : result){
        std::cout << ele.first << "\t:\t" << ele.second<<std::endl;
        }*/
    for (int i = 0; i <= 9; i++){
        if (result.find(i) == result.end()){
            std::cout << i << " : " << 0 << std::endl;
            continue;
        }
        std::cout << i << " : " << result.at(i)<< std::endl;
    }
}

int main(int argc, char** argv)
{
    InputVector input{ 10, 11, 12, 13, 14, 15 };
    ResultMap result;

    countNumbers1(input, result);
    showResult(result);
    return 0;
}

c++풀이입니다. 대상이 되는 정수들로 채워진 vector를 입력으로하고 [int-->int]로 mapping되는 map을 출력으로하는 countNumbers1이라는 함수를 만들었습니다. 숫자 카운트는 정수를 문자열로 바꿔서 수행하였습니다.

2016/10/04 15:17

LEE JaeJun

#include<iostream>

using namespace std;

int main()
{

    int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };

    for (int i = 0;i < 10;i++)
        arr[i] = 0;

    for (int i = 1;i < 1001;i++)
    {
        if (i >= 1 && i < 10)
            arr[i]++;
        else if (i >= 10 && i < 100)
        {
            arr[i / 10]++;
            arr[i % 10]++;
        }
        else if (i >= 100 && i < 1000)
        {
            arr[i / 100]++;
            arr[(i / 10)-((i/100)*10)]++;
            arr[i % 10]++;
        }
        else if (i == 1000)
        {
            arr[1]++;arr[0] += 3;
        }
    }

    for (int i = 0;i < 10;i++)
        cout << i << "의 개수 : " << arr[i] << endl;

    return 0;
}

//0의 개수 :192
//1의 개수 :301
//2의 개수 :300
//3의 개수 :300
//4의 개수 :300
//5의 개수 :300
//6의 개수 :300
//7의 개수 :300
//8의 개수 :300
//9의 개수 :300

2016/10/07 21:50

marshawnLynch

include

int main() { int num,i,j,cnt=0, k,num1;

int num_arr[10];

//배열 0으로 초기화
for(i = 0; i<10; i++) {
    num_arr[i] = 0;
}

printf("입력개수: ");
scanf("%d", &num1);

// 입력받은 숫자 자릿수 count# 
for(j = 0; j<num1; j++) {
    printf("숫자 입력:"); 
    scanf("%d", &num);

    k = num;
    while(k != 0) {
        //k = k % 10;
        for(i = 0; i<10; i++) {
            if((k%10) == i) {
                num_arr[i]++;
            }
        }
        k = k /10;
    }
}

    for(i = 0; i<10; i++) {
        printf("%d : %d\n", i, num_arr[i]);
    }

return 0;

}

2016/10/10 01:12

박소정

package codingdojang;

import java.util.ArrayList;

public class One_1to_1000 {

    public static void main(String[] args) {

        ArrayList<String> numList= new ArrayList<String>();//1~1000을 string형으로 저장할 list
        int[] chkNum = new int[10]; //0~9 를 몇개씩 갖는지 저장할 배열
        for (int i = 10; i <=15; i++) {
            numList.add(i+""); //i+""를통해 숫자를 String형으로 변환하여 list에 저장.
        }

        for (int i = 0; i <numList.size(); i++) {
            for (int j = 0; j < numList.get(i).length(); j++) {
                String temp = numList.get(i).substring(j, j+1);
                if(temp.equals("0")){
                    chkNum[0]++;
                }
                else if(temp.equals("1")){
                    chkNum[1]++;
                }
                else if(temp.equals("2")){
                    chkNum[2]++;
                }
                else if(temp.equals("3")){
                    chkNum[3]++;
                }
                else if(temp.equals("4")){
                    chkNum[4]++;
                }
                else if(temp.equals("5")){
                    chkNum[5]++;
                }
                else if(temp.equals("6")){
                    chkNum[6]++;
                }
                else if(temp.equals("7")){
                    chkNum[7]++;
                }
                else if(temp.equals("8")){
                    chkNum[8]++;
                }
                else if(temp.equals("9")){
                    chkNum[9]++;
                }
            }
        }//for

        for (int i = 0; i < chkNum.length; i++) {
            System.out.println(chkNum[i]);
        }

    }

}
//1~1000에서 각 숫자의 개수 구하기
//
//예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자
//
//10 = 1, 0
//11 = 1, 1
//12 = 1, 2
//13 = 1, 3
//14 = 1, 4
//15 = 1, 5
//
//그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개

2016/10/11 11:33

주상곤

start = 1
end = 1000

x = str(list(range(start, end+1)))

for i in range(0, 10) :
    print("%d ==> %3d" % (i, str(x).count(str(i))))



2016/10/13 01:32

Kim TaeWoo

public class NumberCount {
    public static void main(String[] args) {
        int[] result = new int[10];

        for(int i=1; i <=1000; i++){
            if(i/1000 > 0){
                result[(i/1000)]++;
                result[((i%1000)/100)]++;
                result[((i%100)/10)]++;
                result[(i%10)]++;
            }else if(i/100 > 0){
                result[(i/100)]++;
                result[((i%100)/10)]++;
                result[(i%10)]++;
            }else if(i/10 > 0){
                result[(i/10)]++;
                result[(i%10)]++;
            }else{
                result[i]++;
            }
        }

        for(int i=0; i < result.length ; i++){
            System.out.println(i + " :" +  result[i] + " 개");
        }
    }
}

2016/10/13 03:39

이동규

from collections import defaultdict

d = defaultdict(int)
for n in range(1, 1001):
    for x in str(n):
        d[int(x)] += 1

for i in range(10):
    print(i, ":", d[i], "개")

2016/10/13 13:53

훠니

from itertools import chain

def num_counter(start,end):
    temp_list = [ list(str(i)) for i in range(start,end+1)]
    temp_flat_list = list(chain.from_iterable(temp_list))
    count_list = [ temp_flat_list.count(str(i)) for i in range(0,10) ]
    print(count_list)

num_counter(1,1000)

2016/10/17 01:14

조종섭

public class Aha {
    public static void main(String[] args) {
        String x = "";
        int cnt0 = 0;
        int cnt1 = 0;
        int cnt2 = 0;
        int cnt3 = 0;
        int cnt4 = 0;
        int cnt5 = 0;
        int cnt6 = 0;
        int cnt7 = 0;
        int cnt8 = 0;
        int cnt9 = 0;

        int i, j;

        for (i = 1; i < 1001; i++) {
            x += i;
        }

        for (j = 0; j < x.length(); j++) {
            System.out.println("charAt" + j + "> " + x.charAt(j));
            if (x.charAt(j) == '0')
                cnt0++;
            if (x.charAt(j) == '1')
                cnt1++;
            if (x.charAt(j) == '2')
                cnt2++;
            if (x.charAt(j) == '3')
                cnt3++;
            if (x.charAt(j) == '4')
                cnt4++;
            if (x.charAt(j) == '5')
                cnt5++;
            if (x.charAt(j) == '6')
                cnt6++;
            if (x.charAt(j) == '7')
                cnt7++;
            if (x.charAt(j) == '8')
                cnt8++;
            if (x.charAt(j) == '9')
                cnt9++;
        }
        System.out.println("0 의 갯수> " + cnt0);
        System.out.println("1 의 갯수> " + cnt1);
        System.out.println("2 의 갯수> " + cnt2);
        System.out.println("3 의 갯수> " + cnt3);
        System.out.println("4 의 갯수> " + cnt4);
        System.out.println("5 의 갯수> " + cnt5);
        System.out.println("6 의 갯수> " + cnt6);
        System.out.println("7 의 갯수> " + cnt7);
        System.out.println("8 의 갯수> " + cnt8);
        System.out.println("9 의 갯수> " + cnt9);
        System.out.println(x);
    }
}

2016/10/20 10:47

KIM

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

namespace std {
    inline char* to_string(int value) {
        static char buffer[4] = {0};
        sprintf(buffer, "%4d", value);
        return buffer;
    }
};

int main() {
    int count[10] = {0};
    char* string = NULL;

    for (int i=1; i<=1000; i++) {
        string = std::to_string(i);
        count[string[0]-48] += 1;
        count[string[1]-48] += 1;
        count[string[2]-48] += 1;
        count[string[3]-48] += 1;
    }

    for (int i=0; i<10; i++) {
        printf("%d has %d\n", i, count[i]);
    }
}


[OUTPUT]
0 has 192
1 has 301
2 has 300
3 has 300
4 has 300
5 has 300
6 has 300
7 has 300
8 has 300
9 has 300

2016/10/23 23:42

김 민수

public class Main {

    public static void main(String[] args) {

        int[] numberCount = new int[10];
        int len = numberCount.length;

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

            numberCount[i] = 0;

        }

        for (Integer i = 1; i <= 1000; i++) {

            char[] tmp = i.toString().toCharArray();
            int length = tmp.length;

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

                numberCount[(int) (tmp[j] - '0')]++;

            }
        }

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

            System.out.print(i + " : " + numberCount[i] + "  ");
        }
    }

}

2016/10/27 00:01

김 수호

python으로 작성하였습니다. 0 192 1 301 2 300 3 300 4 300 5 300 6 300 7 300 8 300 9 300

num={}
for i in range(0,10):
   num[i]=0
   for r in range(1,1001):
      for r2 in str(r):
         num[int(r2)]=num[int(r2)]+1
print num

2016/10/28 14:20

도르르

package test001;

public class ManipulateArray {
    protected int getLength(int num) {
        return (int) (Math.log10(num) + 1);
    }

    protected void setArrayData(int[] arr, int inputNum) {
        int length = getLength(inputNum);

        for (int i = 0; i < length; i++) {
            arr[inputNum % 10]++;
            inputNum /= 10;
        }
    }

    public int[] getArrayData(int lowNum, int highNum) {
        int[] arr = new int[10];

        for (int i = lowNum; i <= highNum; i++) {
            setArrayData(arr, i);
        }

        return arr;
    }

    public static void main(String[] args) {
        int[] arr = new ManipulateArray().getArrayData(1, 1000);

        for (int i = 0; i < arr.length; i++) {
            System.out.println(i + ":" + arr[i]);
        }
    }
}

0:192 1:301 2:300 3:300 4:300 5:300 6:300 7:300 8:300 9:300

2016/10/29 21:42

얌얌

#include <stdio.h>

void numCount(int start, int end);

int main()
{
    int start, end;

    printf(" 범위 : ");
    scanf("%d %d",&start, &end);

    numCount(start, end);
}

void numCount(int start, int end) 
{
    int num[10] = {0};
    int count = 0;
    for(int i=start; i<=end; i++)
    {
        if (i == 1000) {
            num[0] += 3;
            num[1] ++;
        }
        else if(i >= 100 && i<=999) {
            num[i/100]++;
            num[(i%100)/10]++;
            num[(i%10)]++;
        }
        else if(i>=10 && i<=99) {
            num[i/10]++;
            num[i%10]++;
        }
        else num[i]++;
    }

    for(int j=0 ; j<10 ; j++ ) {
        printf("num[%d] : %d \n", j,num[j]); 
    }

}



2016/10/30 03:58

오씨

python 2.X로 작성했습니다.

# 빈 리스트를 만듭니다.
result = []

# 숫자를 쪼갠 후, 빈리스트에 문자열로 저장합니다. 예를 들면 11을 '1' , '1'로 121을 '1', '2', '1'로 쪼갠후 result에 저장합니다.
for n in xrange(1, 1001):
    for x in xrange(len(str(n))):
        result.append(str(n)[x])

# 0부터 9까지 출력하고, 이 문자열(숫자)에 해당하는 숫자를 count합니다.
for i in xrange(0, 10):
    print str(i) + ':', result.count(str(i))

2016/10/31 20:00

페르난도

class Practice01{
    public static void main(String[] args){
        int[] cnt=new int[10];
        for (int i=1;i<=1000;i++){
            if (i<10){
                cnt[i%10]++;
            }else if (i>=10 && i<100){
                cnt[i/10]++;
                cnt[i%10]++;
            }else if (i>=100 && i<1000){
                cnt[i/100]++;
                cnt[(i%100)/10]++;
                cnt[(i%100)%10]++;
            }else if (i==1000){
                cnt[i/1000]++;
                cnt[0]=cnt[0]+3;
            }
        }
        for (int i=0;i<cnt.length;i++){
            System.out.println(i+": "+cnt[i]+"개");
        }
    }
}

2016/11/01 00:07

이 대균

안녕하세요. 뉴비입니다. C++로 풀어봤어요

#include<iostream>

using namespace std;

void main()
{
    cout<<"Hello Stranger??"<<endl;

    int cntNum[10] = {0};

    for(int i=1; i<=1000; i++)
    {
        int num = i;
        while(true)
        {
            int val = num%10;
            cntNum[val]++;

            num = num/10;
            if( num==0 )
                break;      
        }
    }

    for(int i=0; i<10; i++)
        cout<<"["<<i<<"] "<<cntNum[i]<<endl;
}

[0] 192 [1] 301 [2] 300 [3] 300 [4] 300 [5] 300 [6] 300 [7] 300 [8] 300 [9] 300

2016/11/01 18:13

이재웅

def countnum(n,m):
    result = [0,0,0,0,0,0,0,0,0,0]
    for num in range(n,m+1):
        s_num = str(num)
        for i in range(0,10):
            j = str(i)
            fac_num = s_num.count(j)
            result[i] = result[i] + fac_num

    return result

2016/11/02 10:30

김현남

number = [0,0,0,0,0,0,0,0,0,0]
k = 11
for i in range(0,k+1):
    j = 0
    if len(str(i)) <= len(str(k)):
        while(i >= 10):
            j = i%10
            number[j] = number[j] + 1
            i = i/10
    number[i] = number[i] + 1
print(number)

2016/11/02 10:55

mch

#include <iostream>
using namespace std;

int main ()
{
    int counter = 0;
    int digitArr[10];

    for (counter = 0; counter < 10; counter++) {
        digitArr[counter] = 0;
    }

    for (counter = 1; counter < 1001; counter++) {
        if ((counter/100) > 0) {
            if (counter/1000 > 0)
            {
                digitArr[counter/1000] += 1;
                digitArr[(counter%1000)/100] += 1;
                digitArr[((counter%100)/10)] += 1;
                digitArr[(counter%10)] += 1;
            }
            else {
                digitArr[(counter/100)] += 1;
                digitArr[((counter%100)/10)] += 1;
                digitArr[(counter%10)] += 1;
            }
        }
        else if ((counter/10) > 0) {
            digitArr[(counter/10)] += 1;
            digitArr[(counter%10)] += 1;
        }
        else if (counter > 0) {
            digitArr[counter] += 1;
        }
        else
            digitArr[0] += 1;
    }

    for (counter = 0; counter < 10; counter++) {
        cout << counter << "의 갯수 : " << digitArr[counter] << endl;
    }
    return 0;
}

2016/11/02 16:16

seo bum seok

def NumCount(a,b):
    tot0=0
    tot1=0
    tot2=0
    tot3=0
    tot4=0
    tot5=0
    tot6=0
    tot7=0
    tot8=0
    tot9=0

    for i in range(a,b+1):
        A=list(str(i))

        if '0' in A:
            tot0+=A.count('0')
        if '1' in A:
            tot1+=A.count('1')
        if '2' in A:
            tot2+=A.count('2')
        if '3' in A:
            tot3+=A.count('3')
        if '4' in A:
            tot4+=A.count('4')
        if '5' in A:
            tot5+=A.count('5')
        if '6' in A:
            tot6+=A.count('6')
        if '7' in A:
            tot7+=A.count('7')
        if '8' in A:
            tot8+=A.count('8')
        if '9' in A:
            tot9+=A.count('9')

    return {0:tot0, 1:tot1, 2:tot2, 3:tot3, 4:tot4, 5:tot5, 6:tot6, 7:tot7, 8:tot8, 9:tot9}

x=1
y=1000
print(NumCount(x,y))

2016/11/03 11:29

박 상민

1~1000에서 각 숫자의 개수 구하기

int main(int argc, const char * argv[]) {
    int numDigits[10] = {0,};
    for (int i=1; i<=1000; i++) {
        countDigits(i, numDigits);
    }
    for (int i=0; i<10; i++) {
        printf("%d: %d\n", i, numDigits[i]);
    }
    return 0;
}
void countDigits(int n, int numDigits[]) {
    do {
        int digit = n % 10;
        numDigits[digit]++;
        n /= 10;
    } while (n > 0);
}

2016/11/03 21:56

Han Jooyung

10으로 나누면서 10의 나머지로 자리수를 확인해서 카운트

import static org.junit.Assert.assertEquals;

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

import org.junit.Test;

public class CountNumber {

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

    public Map<Integer, Integer> countNumber(final int start, final int end) {
        Map<Integer, Integer> result = new HashMap<>();

        for(int i = start; i <= end; i++) {
            int number = i;

            while(number != 0) {
                int index = number % 10;

                if(result.containsKey(index))
                    result.put(index, result.get(index) + 1);
                else
                    result.put(index, 1);   

                number /= 10;
            }
        }

        return result;
    }

    @Test
    public void testCountNumber() {
        Map<Integer, Integer> expected = new HashMap<>();

        expected.put(0, 1);
        expected.put(1, 7);
        expected.put(2, 1);
        expected.put(3, 1);
        expected.put(4, 1);
        expected.put(5, 1);

        assertEquals(expected, countNumber(10, 15));
    }
}

2016/11/04 13:20

한비타

#include <iostream>

using namespace std;
int numberOfNum(int n, int from, int to){
    int temp;
    int result=0;
    for(from;from<=to;from++){
        temp = from;
        while(temp!=0){
            if(temp%10==n)result++;
            temp/=10;
        }
    }
    return result;
}
int main()
{
   for(int i=0;i<10;i++){
       cout<<i<<"갯수 : "<<numberOfNum(i,10,15)<<endl;
   }
   return 0;
}


C++로 작성했습니다.

2016/11/06 02:58

하 종희

java8로 작성했고 NumberCount.java를 실행하면 Console화면으로 결과를 볼 수 있습니다.

public class NumberCount {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5);
        Map<Integer, Integer> map = numbers.stream().collect(groupingBy(Function.identity(), summingInt(e -> 1)));
        map.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));
    }
}

2016/11/11 08:51

KIM YONG HOON

public class Main {
    public static final int MAX_RANGE = 1000;
    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] numArray = new int[10];
        Arrays.fill(numArray,0);

        for(int i = 1 ; i < MAX_RANGE+1; i++){
            String nums = String.valueOf(i);

            for(char num : nums.toCharArray()){
                numArray[Integer.parseInt(""+num)] += 1;
            }
        }
        int arrayLength =numArray.length;

        for(int n=0; n < arrayLength;n++){
            System.out.println(n+": "+numArray[n]);
        }
    }

}

2016/11/13 13:11

wishwisdom

#!/usr/bin/python

digit_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0, '0':0}

for num in range(1,1001):
    for digit in str(num):
        digit_dict[digit] += 1

for i in range(10):
    print i,':',digit_dict[str(i)],'ea'

2016/11/14 13:56

바바

/* 자바로 작성했습니다. */
-- CodingRoom.java
import Questions.SumEachNumber;

public class CodingRoom {

    public static void main(String[] args) {

        SumEachNumber sumEachNumber = new SumEachNumber();

        long lStartTime = System.currentTimeMillis(); // start time
        sumEachNumber.setNumber(1, 1000);  // 처음숫자, 끝숫자 
        long lDuration = System.currentTimeMillis() - lStartTime;
        sumEachNumber.printResult();
        System.out.println(String.format("Elapsed Time: %.3f seconds", lDuration/ 1000.0f));
    }
}

-- SumEachNumber.java
package Questions;

import java.util.HashMap;
import java.util.Iterator;

public class SumEachNumber {

    private HashMap<Integer, Integer> hashNumList = null; 

    public SumEachNumber()  {

        hashNumList = new HashMap<Integer, Integer>();
    }
    /**
     * 처음숫자와 종료숫자를 인자로 받아 각 숫자별 개수를 카운트하고 hashNumList에 저장한다.
     * @param startNum
     * @param endNum
     */
    public void setNumber(int startNum, int endNum) {

        for (int i = startNum; i <= endNum; i++)    {
            String num = String.format("%d", i); 

            for (int j = 0; j < num.length(); j++)  {
                int n = Integer.parseInt(String.format("%s", num.charAt(j)));

                if (hashNumList.containsKey(n)) {
                    hashNumList.put(n, hashNumList.get(n) + 1);
                } else {
                    hashNumList.put(n, 1);
                }
            }
        }
    }

        /**
     * hashNumList의 값을 화면에 출력한다. 
     */
    public void printResult()   {

        Iterator<Integer> itr = hashNumList.keySet().iterator();

        while (itr.hasNext())   {
            Integer key = itr.next();
            System.out.println(String.format("Number: %d, Count: %d", key, hashNumList.get(key)));
        }
    }   
}



2016/11/15 13:31

Lee Kyounghee

    public static void main(String[] args) {
        int[] cnt=new int[10];

        for(int i=1;i<=1000;i++){
            Integer temp=i;
            String str[]=temp.toString().split("");
            for(int j=0;j<str.length;j++){
                cnt[Integer.parseInt(str[j])]++;
            }   
            }

        for(int i=0;i<cnt.length;i++){
            System.out.println(i+":"+cnt[i]);

        }

    }


2016/11/15 14:11

신 동리

a=' '
for x in range(1,1001):
    a+=str(x)

for x in range(10):
    print a.count(str(x)


2016/11/17 23:37

류수현

result = [0 for _ in range(10)]
for i in range(1, 1001):
    for digit in str(i):
        result[int(digit)] += 1

for i, value in enumerate(result):
    print(i, value)

2016/11/18 16:53

박인기

def f(n):                                             # 자릿수 풀어서 리스트로 만들기
    li = []
    li.append(int(n/1000))
    li.append(int(n/100)-10*int(n/1000))
    li.append(int(n/10)-10*int(n/100))
    li.append(n%10)
    return li

def count(k, n):                                      # n에 있는 k의 개수 구하기
    result = 0
    if k in range(1, 10):
        for i in range(0, 4):
            if k == f(n)[i]:
                result = result + 1
        return result
    elif k == 0:
        if not f(n)[0] == 0:
            for i in range(1, 4):
                if f(n)[i] == 0:
                    result = result +1
        elif not f(n)[1] == 0:
            for i in range(2, 4):
                if f(n)[i] == 0:
                    result = result +1
        elif not f(n)[2] == 0:
            if f(n)[3] == 0:
                result = result +1
        else:
            result = 0
        return result

def countnumber(k):                                    # 1부터 1000까지 k의 개수 구하기
    result = 0
    for i in range(1, 1001):
        result = result + count(k, i)
    return result


for i in range(10):                                    # 답 출력
        print("%s의 개수는 %s"%(i,countnumber(i)))

2016/11/19 18:04

fdn

파이썬 3.5.2

list = [0,0,0,0,0,0,0,0,0,0]

for i in range(1,1001):
    for j in str(i):
        list[int(j)] = list[int(j)]+1

print(list)

2016/11/20 23:04

읍내노는오빠

count = [0]*10
for i in range(1,1000+1):
    for j in str(i):
        count[eval(j)] +=1
print(count)

2016/11/21 16:22

Makery

{str(x):str(list(range(1, 1001))).count(str(x)) for x in range(0,10)}

Python 2.7.12, Python 3.5.2에서 확인했습니다.

2016/11/22 12:23

Yeo HyungGoo

start, end = input("please press num(start, end)")
num = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for i in range(start, end + 1):
    for j in range(len(str(i))):
        int1 = int(str(i)[j])
        num[int1] = num[int1] + 1

for i in range(10):
    if num[i] != 0:
        print i, ':', num[i]

2016/11/22 15:11

Seo dong-in

arr = {}

for i in range(1, 1001) :
    for j in str(i) :
        if j in arr :
            arr[j] += 1
        else :
            arr[j] = 1

print(arr)

2016/11/27 17:28

하얀운동화

print("Please input 2 numbers :", end=' ')
a, b = input().split()

dic = {}
for i in range(int(a), int(b)+1):
    for y in str(i):
        if dic.get(y) == None:
            dic[y] = 0
        dic[y] += 1

for i in sorted(dic):
    print("%s : %s ea" % (i, dic[i]))

2016/11/28 08:48

Tomket

include

void main() { int i; int a[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

for (i = 1; i <= 1000; i++) { int d = i; while(1) { a[d%10]++; d = d/10; if (d == 0) break; } }

for (i = 0; i < 10; i++) { printf("%d : %d개 ", i, a[i]); } }

2016/11/30 09:43

리코둔

public class Number {
    public static void main(String[] args) {
        int a[] = new int[10];
        for(int i=1; i<1001; i++){
            if(i<10){
                a[i]++;
            }
            else if(i<100){
                a[i/10]++;
                a[i%10]++;
            }
            else if(i<1000){ //ex)687
                int j=i/100; // 6
                int k=100*j;// 600
                int m=i%k; // 87
                int l = m/10; // 8
                if(m>=10){
                    a[j]++; //첫째자리
                    a[l]++;//둘째자리
                    a[m%10]++;//마지막자리
                }
                else{
                    a[j]++;
                    a[0]++;
                    a[m]++;
                }

            }
            else if(i==1000){
                a[0]++;
                a[0]++;
                a[0]++;
                a[1]++;
            }
        }
        for(int i=0; i<10; i++){
            System.out.print(i+":");
            System.out.print(a[i]);
            System.out.println();
        }
    }

}

2016/11/30 23:58

정 진석

눕눕이가 작성해본 파이썬입니다.

s = []# 리스트 생성!!!

for i in range(1,1000+1):
    x = str(i)
    s.extend(x[0:]

for v in range(10): #1~9
    print(v, ":", s.count(str(v)), "개")

2016/12/05 07:12

Kim Soojong

java8로 작성했습니다.

실행결과

key : 0, value : 192
key : 1, value : 301
key : 2, value : 300
key : 3, value : 300
key : 4, value : 300
key : 5, value : 300
key : 6, value : 300
key : 7, value : 300
key : 8, value : 300
key : 9, value : 300

public class Basic504_2 {
    public static void main(String[] args) {
        Map<String, Integer> resultMap = new HashMap<>();

        IntStream.iterate(1, i -> i + 1).limit(1000).forEach(
                i -> {
                    if(i > 9) {
                        String share = Integer.toString(i / 10);
                        for (int x = 0; x < share.length(); x++) {
                            putData(resultMap, Character.toString(share.charAt(x)));
                        }
                    }

                    String rest = Integer.toString(i % 10);
                    putData(resultMap, rest);
                }
        );

        for (Map.Entry<String, Integer> entry : resultMap.entrySet()) {
            System.out.println("key : " + entry.getKey() + ", value : " + entry.getValue());
        }
    }

    private static void putData(Map<String, Integer> map, String data) {
        if (map.get(data) == null) {
            map.put(data, 1);
        } else {
            map.put(data, map.get(data) + 1);
        }
    }
}

2016/12/05 23:21

KIM YONG HOON

package min;

class InputNum {
    private int num1;
    private int num2;
    private int[] resultArr = {0,0,0,0,0,0,0,0,0,0};

    public InputNum(int num1, int num2) {
        this.num1 = num1;
        this.num2 = num2;
    }

    public int[] result() {
        if(this.num1 < this.num2) {
            for(int i = this.num1; i <= this.num2; i++) {
                char[] numArr = String.valueOf(i).toCharArray();
                for(int j = 0, size = numArr.length; j < size; j++) {
                    this.resultArr[numArr[j] - 48]++;
                }
            }
        } else {
            int num3 = this.num1;
            this.num1 = this.num2;
            this.num2 = num3;
            this.result();
        }
        return resultArr;
    }
}

public class NumberTest {
    public static void main(String args[]) {
        int[] arr = new InputNum(1, 1000).result();
        for(int i = 0; i < 10; i++) {
            System.out.println(i + " 갯수 : " + arr[i]);
        }
    }
}

0 갯수 : 192

1 갯수 : 301

2 갯수 : 300

3 갯수 : 300

4 갯수 : 300

5 갯수 : 300

6 갯수 : 300

7 갯수 : 300

8 갯수 : 300

9 갯수 : 300

2016/12/09 17:53

Eunjung Ji

b=[]
for a in range(1, 1001):
    b.append(a)
c = str(b)
print '0 is', c.count('0')
print '1 is', c.count('1')
print '2 is', c.count('2')
print '3 is', c.count('3')
print '4 is', c.count('4')
print '5 is', c.count('5')
print '6 is', c.count('6')
print '7 is', c.count('7')
print '8 is', c.count('8')
print '9 is', c.count('9')

2016/12/11 17:06

Jang Young Sun

nums = list(input())
print({x :nums.count(str(x)) for x in range(0,10)})

#### 2016.12.13 D-436 ####

2016/12/13 23:23

GunBang


Python 3.5

dict = {}
for i in range(10):
    dict[i] = 0
for num in range(1,1001):
    for pa in str(num):
        dict[int(pa)] += 1

for total in range(10):    //    Printing
    print("%d = %d" % (total,dict[total]))

print(dict)
input()


// Result

0 = 192
1 = 301
2 = 300
3 = 300
4 = 300
5 = 300
6 = 300
7 = 300
8 = 300
9 = 300
{0: 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300}

2016/12/15 00:02

code

public class test {

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

        int sum = 0;
        int[] arr = new int[10];
        for(int i=1; i<=1000; i++){
            int num = i;

            while(num!=0){
                arr[num%10] += 1;                   
                num /= 10;
            }
        }
        for(int i=0; i<arr.length; i++){
            System.out.println(i+": "+arr[i]);
        }
    }
}

2016/12/16 15:31

박소정

num_list = []
for i in range(10):
    num_list.append(0)
for j in range(1,1001):
    if j < 10:
        num_list[j] += 1
    elif j>= 10 and j < 100:
        num_list[j/10] += 1
        num_list[j%10] += 1
    elif j >= 100 and j < 1000:
        num_list[j/100] += 1
        num_list[(j%100)/10] += 1
        num_list[(j%100)%10] += 1
    else:
        num_list[0] += 3
        num_list[1] += 1
for i in range(len(num_list)):
    print ('%d 개수: %d'%(i,num_list[i]))

2016/12/16 17:19

kkwon

package countnumbers;

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

/ * @author kr055045 / public class CountNumbers { static int MAX_NUM = 1000; / * @param args the command line arguments */ public static void main(String[] args) { Map list = new HashMap();

    //init map
    initList(list);
    for (int i= 0; i<=MAX_NUM ; i++){
        sortList(list, i);
    }

    for(int i =0; i<list.size(); i++){
        System.out.println(i + " :" + list.get(String.valueOf(i)));
    }


}

public static void sortList(Map list, int n){
    String temp = Integer.toString(n);

    for(int i =0; i<temp.length(); i++){
        String tempKey = String.valueOf(temp.charAt(i));
        int cntNum;
        cntNum = (int)list.get(tempKey);
        cntNum++;
        System.out.println(cntNum);
        list.put(tempKey, cntNum);
    }

}

public static void initList(Map list){
    for (int i=0; i<10; i++){
        list.put(String.valueOf(i), 0);
    }
}

}

2016/12/19 10:14

Kim Joosang


public class MainTest {

    public static void main(String[] args) {
        int target = 100;
        int[] list = new int[target];
        int[] result = new int[10];
        for(int x = 0; x < list.length; x++){
            list[x] = x;
        }
        for(int x = 0; x < result.length; x++) {
            result[x] = 0;
        }
        for(int x = 1; x < list.length+1; x++){
            char[] c = (""+x).toCharArray();
            for(char j:c){
                result[Character.getNumericValue(j)] += 1;
            }
        }
        for(int i:result){
            System.out.println(i);
        }
    }
}

2016/12/19 21:53

평온한스

def count_onebyone(x):
    count=0
    for y in range(1,1001):
        count+=str(y).count(str(x))
    return x, count

if __name__ == "__main__":
    for x in range(10):
        print("%d은 %d번 나옵니다." % count_onebyone(x))

2016/12/20 06:07

박 시우

/* 
1~1000에서 각 숫자의 개수 구하기
13
 추천
Lv. 1
예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자

10 = 1, 0
11 = 1, 1
12 = 1, 2
13 = 1, 3
14 = 1, 4
15 = 1, 5

그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개
 */

import java.util.Scanner;

public class Coading1 {
    public static void check(int[] a, int nMod) {

        switch(nMod) {
        case 0: 
            a[0]++;
            break;
        case 1: 
            a[1]++;
            break;
        case 2: 
            a[2]++;
            break;
        case 3: 
            a[3]++;
            break;
        case 4: 
            a[4]++;
            break;
        case 5: 
            a[5]++;
            break;
        case 6: 
            a[6]++;
            break;
        case 7: 
            a[7]++;
            break;
        case 8: 
            a[8]++;
            break;
        case 9: 
            a[9]++;
            break;
        }
    }

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

        int[] nSu = new int[10];
        int[] nMod = new int[4];
        int nMok = 0;

        for (int i = 1; i <= 1000; i++) {
            int j = 0;
            nMok = i;

            while( nMok > 0 ) {
                check(nSu, nMok%10);
                nMok = nMok / 10;       
            }
        } // for end

        for(int i = 0; i < 10; i++)
            System.out.println(i + " = " + nSu[i]);
    }

}

2016/12/20 11:42

김성곤

#include<stdio.h>
#define MAX 1000
int main(void)
{
    int i,j;
    int arrange[10] = { 0 };

    for (i = 1; i <= MAX; i++)
    {
        j=i;
        while (j != 0)
        {
            arrange[j % 10]++;
            j = j / 10;

        }
    }

    for (i = 0; i<10; i++)
        printf("%d의값은 %d개입니다 \n", i, arrange[i]);
    return 0;
}

2016/12/20 12:10

oh

public class RecursiveExample {

public final static int MOD_NUMBER = 10;

public static void main(String[] args) {
    RecursiveExample example = new RecursiveExample();
    Scanner scanner = new Scanner(System.in);
    int number1 = scanner.nextInt();
    int number2 = scanner.nextInt();
    int numberCount[][] = new int[10][1];

    for(int i= number1 ; i <=number2 ; i++){
        example.remainderRecursive(i, numberCount);
    }

    for (int i = 0; i < numberCount.length; i++) {
        System.out.println(i+" count : "+numberCount[i][0]);
    }

}

private void remainderRecursive(int number, int numberCount[][]){
    int q = (number % MOD_NUMBER);
    int r = (number / MOD_NUMBER);

    numberCount[q][0] = numberCount[q][0]+1;
    if(r==0)
        return;
    remainderRecursive(r, numberCount);
}

}

2016/12/23 17:08

초급

c언어로 해봤습니다.

#include <stdio.h>

int Num[10];

void Divide_Num(int a) {                //a를 한자리수, 두자리수, 세자리수, 1000 으로 나누고 
    int i,n_1,n_2,n_3;              // 두자리수 이상일 경우 각 자리수로 분해하여 숫자를 센다.
    if (a < 10) {
        for (i = 0; i <= 9; i++)
            if (a == i)Num[i] += 1;
    }
    else if (10 <= a&&a < 100) {
        for (i = 0; i <= 9; i++) {
            n_1 = a / 10;
            if (n_1 == i)Num[i] += 1;
            n_2 = a%(10*n_1);
            if (n_2 == i)Num[i] += 1;
        }
    }
    else if (100 <= a&&a < 1000) {
        for (i = 0; i <= 9; i++) {
            n_1 = a / 100;
            if (n_1 == i)Num[i] += 1;
            n_2 = a % (100 * n_1);
            if (n_2 == 0) {                            //여기서 이렇게 나눈 이유는 첫번째와 두번째 자리수가 0이면
                if(0==i)Num[i] += 2;               //런타임 오류가 나오기때문에 나누어 주었습니다.
            }
            else if(n_2<10){
                n_3 = n_2 / 10;
                if(n_3==i)Num[i] += 1;
                if (n_2 == i)Num[i] += 1;
            }
            else {
                n_3 = n_2 / 10;
                if (n_3 == i)Num[i] += 1;
                if ((n_2 % (10 * n_3)) == i)Num[i] += 1;
            }
        }
    }
    else if (a == 1000) {
        Num[1] += 1;
        Num[0] += 3;
    }
}

int main() {
    int i, j;
    printf("1~1000에서 각 숫자의 개수 구하기...\n");
    getchar();

    for (i = 0; i <= 9; i++)
        Num[i] = 0;

    for (i = 1; i <= 1000; i++){
        Divide_Num(i);
    }

    for (i = 0; i <= 9; i++)printf("%d : %d\n",i, Num[i]);
}

2016/12/25 00:24

최 윤준

public class SumOfNum {

    public static void main(String[] args) {
        int quotient_old = 0;
        int quotient_new = 0;
        int rest = 0;
        int[] num = new int[10];
        for(int i=1; i<=1000; i++) {
            quotient_old = i;
            while(true) {
                quotient_new = quotient_old / 10;
                rest = quotient_old % 10;
                if(quotient_new == 0) {
                    num[rest]++;
                    quotient_old = quotient_new;
                    break;
                } else {
                    num[rest]++;
                    quotient_old = quotient_new;
                }
            }
        }
        for(int i=0; i<num.length; i++) {
            System.out.println(i + ":" + num[i] + "개");
        }
    }

}

2016/12/27 13:04

derick

#include<iostream>
using namespace std;

void main()
{
    int max, min;
    int X, Y = 0;
    int sum[10][2] = {};

    cout << "최소 숫자를 입력하세요 :";
    cin >> min;
    cout << "최대 숫자를 입력하세요 :";
    cin >> max;

    for (int i = 0; i < 10; i++)
        sum[i][0] += i;
    //최소수부터 최대수까지 계산을 시작

    for (min; min <= max; min++)
    {
        X = min; // 몫
        Y = X % 10; // 나머지

        while (X != 0) {
            for (int i = 0; i < 10; i++) {
                if (sum[i][0] == Y)
                    sum[i][1] += 1;
            }
            X = X / 10;
            Y = X % 10;
        }
    }
    for (int i = 0; i < 10; i++) {
        if (sum[i][1] != 0)
            cout << sum[i][0] << ": " << sum[i][1] << "개 " << endl;
    }
}

2016/12/28 18:43

분당의아들

C(11) gcc v4.9.4

//79COLUMNS////////////////////////////////////////////////////////////////////
// 1~1000에서 각 숫자의 개수 구하기
#include <stdio.h>

void count(int n, int *number);

int main(void)
{
    int number[10] = {[0] = 0};

// 카운트
    for (int n = 1; n <= 1000; n++)
        count(n, number);

// 출력
    for (int i = 0; i < 10; i++)
        printf("[%d] = %d\n", i, number[i]);

    return 0;
}

void count(int n, int *number)
{
    if (! n) return;
    number[n % 10]++;
    count(n / 10, number);
}    

2016/12/29 12:02

디디

자바로 풀었습니다. 문제의 조건에서 입력된 값에 포함된 숫자(예를 들면 19 22의 입력에서는 0, 1, 2, 9만...)만 처리하도록 작성했습니다. 만약 모든 숫자의 갯수가 출력되어야 한다면(0개를 포함한...) 조금 풀이를 바꿔야 할 듯 하네요.

public class CountNumbers {
    public static void main(String[] args) {
        String sNum = "0";
        String eNum = "1000";
        int cNum = Integer.valueOf(sNum);

        Map<String, Integer> countMap = new HashMap<>();

        do {
            char[] charArray = String.valueOf(cNum).toCharArray();
            for(char c : charArray) {
                countNum(countMap, c);
            }
        } while(++cNum <= Integer.valueOf(eNum));

        Set<String> keySet = countMap.keySet();
        for (Object key : keySet) {
            System.out.println(key + ":" + countMap.get(key) + "개");
        }
    }

    private static void countNum(Map<String, Integer> countMap, char currentNum) {
        if(countMap.containsKey(String.valueOf(currentNum))) {
            int count = countMap.get(String.valueOf(currentNum));
            countMap.put(String.valueOf(currentNum), count + 1);
        } else {
            countMap.put(String.valueOf(currentNum), 1);
        }
    }
}

2016/12/30 02:36

Lee SeungChul

python 2.7xxx

import collections,itertools
d = collections.defaultdict(list)
start,end = 10,15
nums = range(start,15+1)
res = collections.Counter(list(itertools.chain(*(map(list,map(str,nums))))))
print res

2016/12/31 14:59

Daniel

public class NumberCount {
    public static void main(String[] args) {
        int[] result = {0,0,0,0,0,0,0,0,0,0};
        for(int i=1; i<=1000; i++) {
            String s = String.valueOf(i);
            for(int j=0; j<s.length(); j++) {
                for(int k=0; k<10; k++) {
                    if(Integer.parseInt(s.substring(j, j+1)) == k)
                        result[k]++;
                }
            }
        }
        for(int i=0; i<10; i++) {
            System.out.println(i+":"+result[i]+"개");
        }
    }
}

2016/12/31 16:00

안현선

package saturdayjava;

public class sat13 { public static void main(String[] args) { int startInput = 1; int endInput = 1000;

    int[] num = new int[10];
    String len = endInput + "";

    for(int idx=startInput; idx<=endInput; idx++) {
        num[idx%10]++;

        // 밑의 if문 주석처리를 for문 하나로 처리
        for(int idx2=1; idx2<len.length(); idx2++) {
            if(idx >= (int)Math.pow(10, idx2)) {
                num[(idx/(int)(Math.pow(10, idx2))) % 10]++;
            }
        }

    }

    for(int idx=0; idx<10; idx++) {
        System.out.println(idx + " : " +  num[idx]);
    }
}

}

2016/12/31 19:02

Min Daehong

python ver 3.5.2

L=[0,0,0,0,0,0,0,0,0,0]
for k in range(1,1001):
    for r in str(k):
        L[int(r)-1]+=1
for a in range(10):
    print('{0}:{1}개'.format(a,L[a]))

2017/01/04 17:14

Exen

$start = 10;
$end = 15;
$array = array();
for($num=$start;$num<=$end;$num++){
    $array = array_merge($array,str_split($num));
}
$num_acount = array_count_values($array);
ksort(array_count_values($array));
foreach($num_acount as $num => $count){
 echo  sprintf("%s:%s개",$num,$count);
 echo "\n";
}

2017/01/04 18:15

stardust

num_str = [] count = [0 for i in range(0,10)]

for i in range(1,1001): num_str.append(str(i))

for i in range(0,1000): for j in num_str[i]: if j in str(range(0,10)): count[int(j)] += 1

for j in range(0,10): print "%s:%s개" %(j, count[j])

2017/01/06 15:51

Lee HyunWoo

l=[0]*10
for i in range(1,1001):
    for c in str(i):l[int(c)]+=1
print(l)

2017/01/08 14:11

Song Seoha

public class NumCount {
    public static void main(String[] args) {
        int Answer[] = new int[10];
        for (int i=0; i<10; i++) {
            Answer[i] = 0;
        }
        for (int i=1; i<=1000; i++) {
            int j = i;
            while (j > 0) {
                int position = j%10;
                Answer[position]++;
                j = j / 10;
            }
        }
        for (int i=0; i<10; i++) {
            System.out.println(i + " : " + Answer[i] + "개");
        }
    }
}

2017/01/08 15:05

Choi Hyoje

public void t504() {
    TreeMap<String, Integer> map = new TreeMap<>();
    for (int inx = 1; inx <= 1000; inx++) {
        String[] strs = Integer.toString(inx).split("");
        for (String str : strs) {
            int cnt = 0;
            if (map.containsKey(str)) {
                cnt = map.get(str);
            }
            map.put(str, cnt + 1);
        }
    }
    for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext();) {
        String key = iter.next();
        int val = map.get(key);
        System.out.println(Integer.parseInt(key) + ": " + val);
    }
}

2017/01/10 10:28

유승욱

// C++

const int MAX_DATA = 10;

bool Func( int nMin, int nMax, int* paBuff )
{
    int nData   = nMin;

    while( nMin <= nMax )
    {
        nData   = nMin;

        while( nData != 0 )
        {
           ++( paBuff[ nData % MAX_DATA ] );

            nData   /= MAX_DATA;
        }

        ++nMin;
    }

    return true;
}

int main()
{
    int nMin  = 0;
    int nMax  = 0;

    cin >> nMin >> nMax;

    int anBuff[ MAX_DATA ] = { 0, };

    Func( nMin, nMax, anBuff );

    for( int x = 0 ; x < MAX_DATA ; ++x )
    {
        cout << x << " : " << anBuff[ x ] << "\n";
    }

    return 0;
}

2017/01/13 16:33

정 훈희

javascript

let count = Array(10).fill().map((_,i) => {
    return {
        key : i,
        value : 0
    };
});

for(let i=1;i<=1000;i++){
    let num = i;
    while(num > 0){
        count[num%10].value += 1;
        num = parseInt(num/10);
    }
}

console.log(count);

2017/01/13 18:40

권혁기

include

int num[10] = { 0 };

int sival(int n) { if (n / 10 >= 1) { araboza(n % 10); return sival(n/10); } araboza(n); return n % 10; }

int araboza(int a) { switch (a) { case 0: num[0]++; break; case 1: num[1]++; break; case 2: num[2]++; break; case 3: num[3]++; break; case 4: num[4]++; break; case 5: num[5]++; break; case 6: num[6]++; break; case 7: num[7]++; break; case 8: num[8]++; break; case 9: num[9]++; break; }

return 0;

}

int main(void) { for (int i = 1; i <= 1000; i++) { sival(i); } for (int i = 0; i < 10; i++) { printf("%d = %d개\n", i, num[i]); }

return 0;

}

2017/01/14 21:09

민영현

var result = new int[10];

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

                while (temp != 0)
                {
                    result[temp % 10]++;
                    temp /= 10;
                }
            }

            for(int i = 0; i < 10; i++)
            {
                Console.WriteLine($"{i} : {result[i]}");
            }

2017/01/16 14:19

오 예천

#include <stdio.h>


void main()
{

    int arr2[10] = { 0, };

    int mok, nam, num1;
    printf("마지막 수 입력 : ");
    scanf_s("%d", &num1);

    for (int i = 0; i <= num1; i++)
    {
        mok = i / 10;
        nam = i % 10;

        arr2[nam] += 1;

        while (mok > 9)
        {
            mok = mok / 10;
            nam = mok % 10;
            arr2[nam] += 1;
        }

        if (mok > 0)
            arr2[mok] += 1;
    }

    printf("0부터 %d까지 \n", num1);
    for (int i = 0; i < 10; i++)
    {

        if(arr2[i] != 0)
        printf("%d : %d개\n", i, arr2[i]);
    }
}

2017/01/19 19:35

정세화

from collections import defaultdict

d = defaultdict(int) for n in range(1, 1001): for x in str(n): d[x] += 1

print(d)

2017/01/22 00:31

쑤어이대

#include <stdio.h>

void main()
{
    int NumCnt[10] = {0, };
    int TenNum = 1;
    int Ten = 10;
    int Cnt = 1;
    int Ans = 0;
    int Ans2 = 0;

    for ( int i = 1; i <= 1000; i++ )
    {
        Ans = i;
        Ans2 = i;
        if ( Ans % Ten == 0 )
        {
            Cnt++;
            Ten *= 10;
        }

        for ( int j = 1; j < Cnt; j++ )
            TenNum *= 10;

        for ( int j = 0; j < Cnt; j++ )
        {
            Ans = Ans / TenNum;
            NumCnt[Ans]++;
            Ans = Ans2 % TenNum;
            TenNum /= 10;
        }
        TenNum = 1;
    }
    for ( int i = 0; i < 10; i++ )
        printf("%d : %d\n", i, NumCnt[i]);
}

2017/01/23 20:50

장예훈

public static void main(String[] args) {
        int[] count = new int[10];
        int a,b;
        for(int i=1;i<=1000;i++){
            if(i<10){
                count[i%10]++;
            }
            else if(i<100){
                count[i/10]++;           //ex) 99 -> count[9]
                count[i%10]++;           //    99 -> count[9]
            }
            else if(i<1000){
                a=i;
                count[a/100]++;          // ex) 834 -> count[8]
                a%=100;                  //     834%100 = 34
                count[a/10]++;           // ex) 34 -> count[3]
                count[a%10]++;
            }
            else{
                a=i;
                count[a/1000]++;
                a%=1000;
                count[a/100]++;
                a%=100;                  
                count[a/10]++;         
                count[a%10]++;
            }
        }
        for(int i=0;i<10;i++){
            System.out.println(i+" : "+count[i]);
        }
    }

2017/01/27 01:25

primary

print [sum([int(y) for y in str(x)].count(z) for x in range(1,1001)) for z in range(10)]

Python 2.7.13

2017/01/27 17:33

PiesP


import java.util.Scanner;

class Calculate{
    int min;
    int max;
    int[] result;
    Calculate(int min,int max) {
        this.min = min;
        this.max = max;
        result = new int[]{0,0,0,0,0,0,0,0,0,0};
    }
    void calc(){
        int num;
        for(int i=min;i<=max;i++){
            num = i;
            while(num != 0){
                this.result[num%10]++;
                num = num/10;
            }
        }

    }
    void showAll(){
        for(int i=0;i<10;i++)
            System.out.println(i+" : "+this.result[i]);
    }
}

public class test {
    public static void main(String[] args) {
        Calculate cal = new Calculate(1, 1000);
        cal.calc();
        cal.showAll();
    }
}

2017/01/27 23:44

김찬

cnt = [0] * 10
nums = ''.join(map(str, range(1, 1001)))
for i in range(0, 10):
    cnt[i]=nums.count(str(i))
    print("%d : %d개" % (i, cnt[i]))

2017/01/31 16:22

seeker

def count_number_simple(number):

    L = [0,0,0,0,0,0,0,0,0,0]
    for x in range(0,number+1):
        for i in str(x):
            L[int(i)] +=1

    for a in range(0,10):
        print str(a) + ':' + str(L[a])

2017/02/07 00:14

임재석

n = [str(num) for num in range(1, 1001)]

numList=[0]*10
for i in range(0,1000):
    for j in range(0,10):
        numList[j]+=n[i].count(str(j))

for i in range(0, 10):
    print('%d : %d개' % (i, numList[i]))

2017/02/07 11:42

Pi jEongHo



    static int[] countNumbers = new int[10];
    static int startNumber = 1;
    static int endNumber = 1000;

    public static void main(String[] args) {

        for (int i = startNumber; i <= endNumber; i++) {
            numberCount(i);
        }
        for (int i = 0; i < countNumbers.length; i++) {
            System.out.println(i + " : " + countNumbers[i]);
        }
    }

    public static void numberCount(int number) {
        countNumbers[number % 10]++;

        if (number >= 10) {
            numberCount(number / 10);
        }
    }

0 : 192 1 : 301 2 : 300 3 : 300 4 : 300 5 : 300 6 : 300 7 : 300 8 : 300 9 : 300

2017/02/09 17:04

김경수

count_list=[0,0,0,0,0,0,0,0,0,0]

for num in range(1,1001):
    for i in str(num): 
      count_list[int(i)] += 1 


for i in range(10):
    print("The number of",i," = ",count_list[i])

2017/02/12 17:34

브이

def number(n):
    result=[]
    for i in range(1,n+1):
        while i>0:
            result+=[i%10]
            i=i//10
    dic={}
    for i in result:
        if i in dic.keys():
            dic[i]+=1
        else:
            dic[i]=1
    print(dic)
number(1000)

2017/02/13 19:10

김구경

#-*- coding: utf-8 -*-
a1=0
a2=0
a3=0
a4=0
a5=0
a6=0
a7=0
a8=0
a9=0
a0=0
for i in range(1,1001):
    a=str(i)
    a1+=a.count('1')
    a2+=a.count('2')
    a3+=a.count('3')
    a4+=a.count('4')
    a5+=a.count('5')
    a6+=a.count('6')
    a7+=a.count('7')
    a8+=a.count('8')
    a9+=a.count('9')
    a0+=a.count('0')
    i+=1
b0=str(a0)
b1=str(a1)
b2=str(a2)
b3=str(a3)
b4=str(a4)
b5=str(a5)
b6=str(a6)
b7=str(a7)
b8=str(a8)
b9=str(a9)

print("0:"+b0+"개")
print("1:"+b1+"개")
print("2:"+b2+"개")
print("3:"+b3+"개")
print("4:"+b4+"개")
print("5:"+b5+"개")
print("6:"+b6+"개")
print("7:"+b7+"개")
print("8:"+b8+"개")
print("9:"+b9+"개")

처음으로 파이썬 배우고 풀어본건데 다른분들에 비해 너무 비교되네요 ^^; 다른분들에게 많이 배워가야겠습니다.

2017/02/14 22:31

mirusu400

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static java.util.stream.Collectors.toList;

public class FromTo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        ArrayList<Integer> numbers = new ArrayList<>();
        IntStream.range(sc.nextInt(), sc.nextInt()+1).forEach(i -> numbers.addAll(Arrays.asList(String.valueOf(i).split("")).stream().map(Integer::valueOf).collect(toList())));
        Map<Integer, Long> map = numbers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(map);
    }
}

2017/02/15 03:07

genius.choi

number = {0:0,
          1:0,
          2:0,
          3:0,
          4:0,
          5:0,
          6:0,
          7:0,
          8:0,
          9:0
}

for num in range(1,1001):
    num_str = str(num)
    for nl in num_str:
        number[int(nl)] += 1

for key in number:
    print(str(key) + ': ' + str(number[key]) + "개")

2017/02/15 23:23

Scott.Jun

/*
date : 17/02/16
dev : peanutBro
content : 1 ~ 1000, Numeric Count
*/

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

const int START_NUMBER = 1;
const int MAX_NUMBER = 1000;

int main(void)
{
    int count[10];

    for (int i = 0; i < 10; i++)
    {
        count[i] = 0;
    }

    for (int i = START_NUMBER; i <= MAX_NUMBER; i++)
    {
        char str[MAX_NUMBER];
        _itoa(i, str, 10);
        for (int j = 0; j < strlen(str); j++)
        {
            count[str[j]-48]++;
        }
    }
    for (int i = 0; i < 10; i++)
    {
        cout << i << " : " << count[i] << "개" << endl;
    }
}

2017/02/16 13:08

강병구 (peanutBro)

import collections

counter = []
for i in range(1, 1001):
    counter += list(str(i))
print collections.Counter(counter)

2017/02/17 22:49

jackson

def convert(strnum):
    return int(strnum)

result = []

for i in range(1001):
    strnum = list(str(i))
    intnum = list(map(convert, strnum))

    result.extend(intnum)

print("0:%d개, 1:%d개, 2:%d개, 3:%d개, 4:%d개, 5:%d개, 6:%d개, 7:%d개, 8:%d개, 9:%d개"
      % (result.count(0), result.count(1), result.count(2), result.count(3), result.count(4), result.count(5), result.count(6), result.count(7), result.count(8), result.count(9)))

2017/02/17 23:10

파이리

digit_number = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for number in range(1, 1001):
    for_count = str(number)
    for index in range(0, 10):
        digit_number[index-1] += for_count.count('%s' % index)

for number in range(0, 10):
    print("number %d :" % number, digit_number[number-1])

OUTPUT number 0 : 192 number 1 : 301 number 2 : 300 number 3 : 300 number 4 : 300 number 5 : 300 number 6 : 300 number 7 : 300 number 8 : 300 number 9 : 300

2017/02/18 00:36

Bongjun Jang

Number_set = [0,0,0,0,0,0,0,0,0,0]

for n in range(1,1001):
    num = str(n)
    for k in range(0,10):
        if str(k) in num:
            Number_set[k]+=1

print(Number_set)

2017/02/18 15:11

sm kim

var dict = {'0':0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0}

for(var num =1; num  <= 1000; num ++){
  if(num>=1 && num < 10){
    z = ((num  % 1000) % 100) % 10;
    ++dict[z];
  }
  else if(num >=10 && num <100){
    y = parseInt(((num  % 1000) % 100) / 10);
    z = ((num  % 1000) % 100) % 10;
   ++dict[y];
   ++dict[z];
  }
  else if(num >=100 && num <1000){
    x = parseInt((num  % 1000) / 100);
    y = parseInt(((num  % 1000) % 100) / 10);
    z = ((num  % 1000) % 100) % 10;
   ++dict[x];
   ++dict[y];    
   ++dict[z];
 }else{
   w = parseInt(num  / 1000);
   x = parseInt((num  % 1000) / 100);
   y = parseInt(((num  % 1000) % 100) / 10);
   z = ((num  % 1000) % 100) % 10;
  ++dict[w];
  ++dict[x];
  ++dict[y];    
  ++dict[z];
 }
}
console.log(dict);

2017/02/20 18:40

Sehun

python 3.5.2

anser is [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

answer = list(0 for x in range(10))
L = list(range(10,16))

for i in range(1,1001) :
    for j in str(i) :
        answer[int(j)] += 1

answer

2017/02/21 11:07

강정민

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    int count[10] = { 0 };
    char buffer[5] = "";

    for (int i = 1; i <= 1000; i++) {
        _itoa_s(i, buffer, 10);
        int length = strlen(buffer);
        for (int j = 0; j < length; j++) {
            count[buffer[j] - '0']++;
        }
    }

    for (int i = 0; i < 10; i++) {
        cout << i << " : " << count[i] << "개" << endl;
    }

    return 0;
}

초보자입니다. C++ 로 풀었습니다. 0 : 192개 1 : 301개 2 : 300개 3 : 300개 4 : 300개 5 : 300개 6 : 300개 7 : 300개 8 : 300개 9 : 300개 결과는 이렇게 나오네요

2017/02/21 16:16

Snow Chris

파이썬 3.6

arr = []
for i in range(1,1001):
    a = ','
    b = a.join(str(i))
    c = b.split(',')
    arr.extend(c)

for j in range(10):
    print (j, ':', arr.count(str(j)))

초급자 수준의 정석...

2017/02/22 19:58

cano

a = []
for i in range(1, 1001):
    for o in str(i):
        a += [o] 

for natural in range(0, 10):
    print(a.count(str(natural)))

2017/02/26 23:27

won jo

#include <stdio.h>



int main()
{
    int count[10] = {};
    int i = 0;
    int one = 0;
    int ten = 0;
    int hundred = 0;
    int thousand = 0;
    printf("1~1000 까지의 각 숫자의 개수를 구해보자:\n");

    for (i = 1; i <= 1000; i++)
    {
        //1의자리
        if (i < 10)
        {
            one = i % 10;
            count[one] += 1;
        }
        //10의자리
        else if ((10 <= i) && (i < 100))
        {
            ten = i / 10;
            count[ten] += 1;

            one = i % 10;
            count[one] += 1;
        }
        //100의자리
        else if ((100 <= i) && (i < 1000))
        {
            hundred = i / 100;
            count[hundred] += 1;

            ten = (i % 100) / 10;
            count[ten] += 1;

            one = (i % 100) % 10;
            count[one] += 1;
        }
        else
        {
            thousand = i / 1000;
            count[thousand] += 1;

            hundred = (i % 1000) / 100;
            count[hundred] += 1;

            ten = ((i % 1000) % 100) / 10;
            count[ten] += 1;

            one = ((i % 1000) % 100) % 10;
            count[one] += 1;

        }
        one = 0;
        ten = 0;
        hundred = 0;
        thousand = 0;
    }
    for (i = 0; i < 10; i++)
    {
        printf("%d 의 갯수: %d\n", i, count[i]);
    }
}

//답은 0 : 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300

2017/02/27 12:06

dong lee

import java.util.Arrays;

public class findNo {

    public static void main(String[] args) {

        // 1~1000에서 각 숫자의 개수 구하기
        int[] noList = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int[] trueList = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        for (int i = 1; i <= 1000; i++) {
            String no = String.valueOf(i);
            for (int j = 0; j < no.length(); j++) {
                int temp = (int) no.charAt(j) - 48;
                for (int k = 0; k < noList.length; k++) {
                    if (temp == noList[k]) {
                        trueList[k] += 1;
                    }
                }
            }
        }
        System.out.println("각 숫자의 갯수 :  " + Arrays.toString(trueList));
    }
}

2017/02/27 16:46

Bradcha

nums = range(1, 1001)
nums_len = list(range(10))
for i in nums_len:
    nums_len[i] = str(list(nums)).count(str(i))
print(nums_len)

nums_len 에 0 부터 9 까지 숫자의 리스트를 만들고, 다시 그 리스트 안에 count 된 수를 넣는 방식입니다.

최종적으로 print 되는 리스트는 0~9까지의 숫자의 갯수를 나타내게 됩니다.

2017/02/28 17:57

최해준

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

        for(int i =0; i<10; i++){
            getNum = 0;
            for(int j = 1; j<= 1000; j++){
                for(int k = 0; k<String.valueOf(j).length();k++){
                    if((int)((j/Math.pow(10,k))%10) == i){
                        getNum++;
                    }
                }
            }
            System.out.println(i+":"+getNum);
        }
    }
}

2017/03/06 15:49

김종철

#입력받는 부분
start = input("input start number: ")
start = int(start)
end = input("input end number: ")
end = int(end)

lst = [0,0,0,0,0,0,0,0,0,0]

for i in range (start,end+1):
    sample = str(i)
    if (i < 100):
        for k in range (2):
            num1 = sample[k]
            num1 = int(num1)
            lst[num1] = lst[num1] + 1

    else:
        for z in range (3):
            num1 = sample[z]
            num1 = int(num1)
            lst[num1] = lst[num1]+1

for j in range (0, 10):
    if(lst[j] == 0):
        continue
    else:
        print("%d:%d개"%(j,lst[j]), end = ' ')



2017/03/07 18:22

christinehong

  1. 찾는 범위의 숫자를 담은 리스트 생성
  2. 리스트를 문자열로 변경
  3. '0' ~ '9' 까지의 char 갯수를 count
def findOccurenceOfDigit( startNum, endNum ):

    result = [ 0 for i in range( 10 )]  # 결과를 담을 컨테이너

    str_list = []

    # 리스트로 초기화 : str_list = [10 11 12 13 14 15]
    for i in range( startNum, endNum + 1  ):
        str_list.append( i )

    # 문자열 리스트로 변경 : str_list = '[10 11 12 13 14 15]'
    str_list = str( str_list )

    # 문자 '0', '1', '2' ... '9' 의 갯수 찾기
    for i in range( 10 ):
        result[i] = str_list.count( str(i) )
        print( "{0} : {1}".format( i, result[i] ))


findOccurentOfDigit( 10, 15 )

2017/03/11 11:39

Ho Lee

#include<stdio.h>

void bitChecker(int n, int* bitList){

int result = n;

while(result>0)
{    
    bitList[result%10]++;
    result = result/10;
}

}

int main(){

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

int bit[10] = {0, };

//bitChecker(1000, bit);

for(i=0;i<1000;i++)
    bitChecker(i+1, bit);

for(i=0;i<10;i++)
    printf("%d의 개수 : %d 개\n", i, bit[i]);

return 0;
}

2017/03/12 13:47

Jin Sung


2017/03/13 08:31

ihong

public class Test1 {
    static void m(int i){
        String st="";
        for(int j=1; j<=1000; j++){
           st += Integer.toString(j);  // String으로 변형해서 문장으로 만듬
        }
        String z = Integer.toString(i); // split을 사용해야해서 string 변수생성
        int cnt = st.split(z).length-1; // 특정문자 갯수구하기
        System.out.print(i+"="+cnt+"개");
    }
    public static void main(String[] args) {
        m(0);
        m(1);
        m(2);
        m(3);
        m(4);
        m(5);
        m(6);
        m(7);
        m(8);
        m(9);
    }
}

답 : 0=189개1=301개2=300개3=300개4=300개5=300개6=300개7=300개8=300개9=300개

2017/03/13 23:28

정승훈

from collections import defaultdict

d = defaultdict(int)
for n in range(1, 1001):
    for x in str(n):
        d[x] += 1

print(d)

2017/03/15 22:15

python 2.7 version

dict = {0 : 0, 1 : 0, 2 : 0, 3 : 0, 4 : 0, 5 : 0, 6 : 0, 7 : 0, 8 : 0, 9 : 0}

for t in range(1, 1001):

a = str(t)

for i in a:
    for y in dict.keys():

        if int(i) == y:
            dict[y] += 1

print dict

2017/03/16 03:02

李愼言(이신언)

include

using namespace std;

int main() { int arr[10] = { 0 };

for (int i = 10; i <= 1000; i++)
{
    if (i >= 1000)
    {
        arr[i % 10] += 1;
        arr[(i % 100) / 10] += 1;
        arr[(i % 1000) / 100] += 1;
        arr[i / 1000] += 1;
    }
    else if (i >= 100)
    {
        arr[i % 10] += 1;
        arr[(i % 100) / 10] += 1;
        arr[i / 100] += 1;
    }
    else if (i >= 10)
    {
        arr[i % 10] += 1;
        arr[i / 10] += 1;
    }
    else
    {
        arr[i % 10] += 1;
    }
}

cout << "각 자리의 갯수 \n";
for (int i = 0; i < 10; i++)
{
    cout << i << "자리 :" << arr[i] << endl;
}

return 0;

}

2017/03/16 11:26

이현섭

from collections import defaultdict

d = defaultdict(int) for n in range(1, 1001): for x in str(n): d[x] += 1

print(d)

2017/03/16 20:47

TV 프론트

from collections import defaultdict

d = defaultdict(int)
for n in range(1, 1001):
    for x in str(n):
        d[x] += 1

print(d)

2017/03/16 21:29

문정민 (◕◡◕)

Java 입니다.


public class Test {

        public static void Excute(){

            int[] row = new int[10];
            Arrays.fill(row, 0);

              for(int i=1;i<1001;i++){
                  String strX = String.valueOf(i);      
                  for(int k=0;k<strX.length();k++){
                     int n = strX.charAt(k)-48;     
                     row[n]+=1;
                  }             
              }

              for(int c=0;c<row.length;c++){
                  System.out.println(c+" : "+row[c]+" 개");
              }          

        }

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

}

2017/03/17 13:11

코코팜팜

box = []
for a in range(1,1001):
    box += list(str(a))
print({x : box.count(str(x)) for x in range(0,10)})

2017/03/18 15:56

ken choi

파이썬으로 작성했어요 제가 올린 사람중에서 코드가 젤 기네요 ㅋㅋㅋㅋ

count0 = 0
count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0
for i in range(1, 5000): 
    a = str(i)
    for j in range(10):
        if j == 0:
            count0 += a.count('0')
        elif j == 1:
            count1 += a.count('1')
        elif j == 2:
            count2 += a.count('2')
        elif j == 3:
            count3 += a.count('3')
        elif j == 4:
            count4 += a.count('4')
        elif j == 5:
            count5 += a.count('5')
        elif j == 6:
            count6 += a.count('6')
        elif j == 7:
            count7 += a.count('7')
        elif j == 8:
            count8 += a.count('8')
        elif j == 9:
            count9 += a.count('9')
print("0의 갯수: %d" % count0)
print("1의 갯수: %d" % count1)
print("2의 갯수: %d" % count2)
print("3의 갯수: %d" % count3)
print("4의 갯수: %d" % count4)
print("5의 갯수: %d" % count5)
print("6의 갯수: %d" % count6)
print("7의 갯수: %d" % count7)
print("8의 갯수: %d" % count8)
print("9의 갯수: %d" % count9)

2017/03/20 12:38

doolki

int div = 0; int cnt = 0; int arr[] = new int[10];

    for(int i = 1; i <= 1000; i++)
    {
        if(i >= 1 && i <= 9)
        {
            arr[i]++;
        }
        if(i >= 10 && i <= 99)
        {                   
            arr[i%10]++;
            arr[i/10]++;
        }
        else if(i>= 100 && i <=999)
        {
            div = i / 10;
            arr[i % 10]++;
            if(div >= 10)
            {
                arr[div%10]++;
                arr[div/10]++;
            }           
        }
        else if(i == 1000)
        {
            div = i / 10;
            arr[i%10]++;

            if(div >= 100)
            {
                div = div / 10;
                arr[div%10]++;
                if(div>=10)
                {
                    arr[div/10]++;
                    arr[div%10]++;
                }
            }

        }
    }       
    for(int i=0; i<arr.length; i++)
    {
        System.out.println(i+":"+arr[i]+"개");
    }
}

노가다로 풀었긴 하지만 효율적인 코드는 아닌거 같습니다...

2017/03/21 15:27

Kwon Steve

include

include

using namespace std;

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

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

for (int i = 0; i < 10; i++)
{
    cout << i << "는 " << num[i] << endl;
}

}

2017/03/25 12:42

PARK JINHOH

파이썬입니다. 숫자입력 받게 했습니다

string = ''
hub=[]

x_1 = input("첫번째 숫자 입력 : ")
x_2 = input("첫번째 숫자 입력 : ")

for x in range(int(x_1),int(x_2) +1,1):
    hub.append(x)

while hub:
    string += str(hub.pop())

print("0 : %d 개" % list(string).count('0'))
print("1 : %d 개" % list(string).count('1'))
print("2 : %d 개" % list(string).count('2'))
print("3 : %d 개" % list(string).count('3'))
print("4 : %d 개" % list(string).count('4'))
print("5 : %d 개" % list(string).count('5'))
print("6 : %d 개" % list(string).count('6'))
print("7 : %d 개" % list(string).count('7'))
print("8 : %d 개" % list(string).count('8'))
print("9 : %d 개" % list(string).count('9'))

2017/03/26 23:35

고든

#include <stdio.h>

int main() {

    int start=1, end=1000, cnt[10] = { 0, };

    int i, temp;

    for (i = start; i <= end; i++) {
        temp = i;
        while (temp) {
            cnt[temp % 10]++;
            printf("%d, ", temp % 10);
            temp /= 10;
        }
        printf("\t");
    }

    printf("\n==============================\n");
    for (i = 0; i < 10; i++)
        printf("%d - %d\n", i, cnt[i]);

}

2017/03/28 09:48

dvv lee

package training;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Vector;

public class GetEachNumCount {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Please insert FIRST Number? ");
        int iNum1 = sc.nextInt();
        System.out.print("Please insert SECOND Number? ");
        int iNum2 = sc.nextInt();
        Vector vec = new Vector();
        for(int i=iNum1; i<=iNum2; i++){
            vec.add(spritNum(i));
        }

        printNumCount(vec);
    }

    // 입력받은 숫자를 분리해서 배열로 저장
    public static ArrayList spritNum(int iNum) {
        String str = String.valueOf(iNum);
        int iStrLength = str.length();

        ArrayList<String> arr = new ArrayList<String>();
        for(int i=0;i<iStrLength;i++){
            arr.add(str.substring(i,  i+1));
        }

        //System.out.println(arr);
        return arr;
    }

    // 결과를 출력한다
    public static void printNumCount(Vector vec) {
        int iZero = 0;
        int iOne = 0;
        int iTwo = 0;
        int iThree = 0;
        int iFour = 0;
        int iFive = 0;
        int iSix = 0;
        int iSeven = 0;
        int iEight = 0;
        int iNine = 0;

        for(int i=0;i<vec.size();i++){
            ArrayList<String> arr = (ArrayList<String>) vec.get(i);
            for(int j=0;j<arr.size();j++){              
                if(Integer.parseInt(arr.get(j)) == 0)
                    iZero++;                
                if(Integer.parseInt(arr.get(j)) == 1)
                    iOne++;
                if(Integer.parseInt(arr.get(j)) == 2)
                    iTwo++;
                if(Integer.parseInt(arr.get(j)) == 3)
                    iThree++;
                if(Integer.parseInt(arr.get(j)) == 4)
                    iFour++;
                if(Integer.parseInt(arr.get(j)) == 5)
                    iFive++;
                if(Integer.parseInt(arr.get(j)) == 6)
                    iSix++;
                if(Integer.parseInt(arr.get(j)) == 7)
                    iSeven++;
                if(Integer.parseInt(arr.get(j)) == 8)
                    iEight++;
                if(Integer.parseInt(arr.get(j)) == 9)
                    iNine++;            
            }
        }

        System.out.println("0 => " + iZero);
        System.out.println("1 => " + iOne);
        System.out.println("2 => " + iTwo);
        System.out.println("3 => " + iThree);
        System.out.println("4 => " + iFour);
        System.out.println("5 => " + iFive);
        System.out.println("6 => " + iSix);
        System.out.println("7 => " + iSeven);
        System.out.println("8 => " + iEight);
        System.out.println("9 => " + iNine);

    }
}

2017/03/28 20:00

acedo

temp=[0,0,0,0,0,0,0,0,0,0]
for num in range(1,1001):
    for tp in (str(num)):
        temp[int(tp)]+=1

for i in range(10):
    print(i,":",temp[i], "개")

2017/03/30 11:05

안대준

count = {x:0 for x in range(0,10)}
for x in range(0,1001):
   for i in str(x):
      count[int(i)]+= 1

print(count)

2017/03/30 13:52

Daeseon Baek

스위프트 되나?

var result: [Int] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for i in 1...1000 {

    let string = Array(String(i).characters)

    for c in string {

        if let index = Int(String(c)) {

            result[index] = result[index] + 1
        }
    }
}

for i in 0...9 {
    print("\(i) : \(result[i])")
}

2017/03/30 14:16

매너홍

from collections import *
d=defaultdict(int)
for x in range(1,1001):
    for n in str(x):
        d[x]+=1
print(d)

2017/04/03 14:58

빅디펜스

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

        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            String input = br.readLine();
            num = Integer.parseInt(input);
        } catch (IOException e) {
            e.printStackTrace();
        }

        int count[] = new int[10];
        for(int i=1; i<=num; i++){
              for(char ch : String.valueOf(i).toCharArray()){
                  count[ch-'0']++;
              }
        }

        for(int i=0; i<10; i++){
              System.out.print(i + ":" + count[i] + "개  " );
        }
    }
}

2017/04/04 13:30

yh

from collections import Counter

def num_list(num):
    num_list1 = []
    i = 0
    while i < num:
        i += 1
        if i < 10:
            num_list1.append(str(i))
        if 10 <= i:
            a = str(i)
            num_list1.append(a[0])
            num_list1.append(a[1])
        if 100 <= i:
            a = str(i)
            num_list1.append(a[0])
            num_list1.append(a[1])
            num_list1.append(a[2])
        if 1000 <= i:
            a = str(i)
            num_list1.append(a[0])
            num_list1.append(a[1])
            num_list1.append(a[2])
            num_list1.append(a[3])
        number = Counter(num_list1)
    return print (number)

num_list(int(input("숫자를입력해주세요")))

..파이썬초보가 파이썬3로 만들어봤습니다. 1000까지가 아닌 1부터 입력받은수까지입니다. 아직 함수정렬은 배우지못해..

2017/04/05 14:17

김도헌

/*
 * 예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자
 * 10 = 1, 0
 * 11 = 1, 1
 * 12 = 1, 2
 * 13 = 1, 3
 * 14 = 1, 4
 * 15 = 1, 5
 * 
 * 그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개
 */
public class Counter {
    public static void main(String[] args) {
        int[] numbers = new int[10];
        for (int i : numbers)
            numbers[i] = 0;
        for (int i = 1; i <= 1000; i++) {
            int j = i;
            while (j > 0) {
                numbers[j % 10]++;
                j = j / 10;
            }
        }
        for (int i = 0; i < 10; i++)
            System.out.println(i + " : " + numbers[i]);
    }
}

정답은 0 : 192 1 : 301 2 : 300 3 : 300 4 : 300 5 : 300 6 : 300 7 : 300 8 : 300 9 : 300

2017/04/06 15:19

디디

#2.py


def sumnum(a,b):
    count = {x:0 for x in range(10)}
    for num in range(a,b+1):
        for n in str(num):
            count[int(n)] +=1
    return count


print(sumnum(10,15))

2017/04/07 23:51

Park Jay

파이썬 3.5입니다.

num0to9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 0부터 9까지 출현하는 갯수를 카운트하기 위해.

for i in range(1, 1001):
    if i < 10 : 
        num0to9[i] += 1 # 10보다 작으면 그 숫자에 해당되는 값을 카운트.
    elif i < 100 : 
        num0to9[i//10] += 1 # 100보다 작으면 일단 십의 자리 값을 찾아서 카운트.
        num0to9[i%10] += 1 # 일의 자리 값을 찾아서 카운트.
    elif i < 1000 :
        num0to9[i//100] += 1 # 1000보다 작으면 일단 백의 자리 값을 찾아서 카운트.
        num0to9[(i%100)//10] += 1 # 십의 자리 값을 찾아서 카운트.
        num0to9[i%10] += 1 # 일의 자리 값을 찾아서 카운트.
    else: # 10000보다 작으면
        num0to9[i//1000] += 1 # 천의 자리 값을 찾아서 카운트. 
        num0to9[(i%1000)//100] += 1 # 백의 자리 값을 찾아서 카운트.
        num0to9[(i%100)//10] += 1 # 십의 자리 값을 찾아서 카운트.
        num0to9[i%10] += 1 # 일의 자리 값을 찾아서 카운트.

for i in range(0, 10):
    print("%d: %d" %(i, num0to9[i])) # 각각 몇개인지 출력. 

결과는 아래와 같습니다.

0: 192 1: 301 2: 300 3: 300 4: 300 5: 300 6: 300 7: 300 8: 300 9: 300

2017/04/09 00:24

simkyohoon

abc = {x:0 for x in range(0,10)}
for number in range(1,1001):
    for s in str(number):
        abc[int(s)] += 1

print(abc)

2017/04/09 14:57

Hyung-Woo Ryoo

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

#define DIGIT_NUM       10                                                         

int main(void)                                                                     
{                                                                                  
        int i;                                                                     
        int j;                                                                     
        int len;                                                                   

        char str[8] = {0, };                                                       
        int arr[DIGIT_NUM] = {0, };                                                

        for (i = 1; i <= 1000; i++)                                                
        {                                                                          
                snprintf(str, sizeof(str), "%d", i);                               
                len = strlen(str);                                                 

                for (j = 0; j < len; j++)                                          
                        arr[str[j] - '0']++;                                       
        }                                                                          

        for (i = 0; i < DIGIT_NUM; i++)                                            
                printf("[%d] : %3d개\n", i, arr[i]);                               

        return 0;                                                                  
}     

c언어 입니다. 배열 index를 활용 해서 카운팅 했어요~

2017/04/09 18:09

by코딩요정

count

count_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for num in range(1,1001): for i in str(num): count_list[int(i)]+=1

for j in range(0,10): print count_list[j]

2017/04/10 15:47

cmcmfl

//c로 풀었음

include

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

int count[10]={0};
int num[10]={0,1,2,3,4,5,6,7,8,9};
int i,j;
int Cn,Cn1;

for (i=0; i<1001; i++)
{
    Cn1=i;

    while (Cn1>9)
    {
        Cn=i%10;
        Cn1=Cn1/10;

        for (j=0; j<10; j++)
        {
            if (Cn==num[j])
            {
                count[j]+=1;
            }
        }
    }

    for (j=0; j<10; j++)
    {
        if (Cn1==num[j])
        {
            count[j]+=1;
        }
    }

}

for (int k=0; k<10; k++) {
    printf("%d의 갯수는 %d\n",k,count[k]);
}

return 0;

}

2017/04/12 15:28

김우진

/*num4~num1 : 각각 천, 백, 십, 일의 자리
             arr : 0~9까지의 갯수를 저장*/
            int num4, num3, num2, num1;
            int[] arr = new int[10];

            for (int i = 1; i < 1001; i++)
            {
                num4 = i / 1000;
                num3 = (i / 100) % 10;
                num2 = (i / 10) % 10;
                num1 = i % 10;

                if (i < 10)
                    arr[num1]++;
                else if (i >= 10 && i < 100)
                {
                    arr[num1]++;
                    arr[num2]++;
                }
                else if (i >= 100 && i < 1000)
                {
                    arr[num1]++;
                    arr[num2]++;
                    arr[num3]++;
                }
                else
                {
                    arr[num1]++;
                    arr[num2]++;
                    arr[num3]++;
                    arr[num4]++;
                }
            }

            for (int i = 0; i < arr.Length; i++)
                Console.WriteLine(i + "의 갯수 : " + arr[i]);

2017/04/14 00:05

얼음별

다른 답안들을 많이 봤는데 대부분 최대 값이 제한되있더라구요.(EX 0 ~ 10,000까지) 이 답안의 경우 최소 값과 최대 값의 제한이 거의 없이(int 범위 제한까지) 모든 숫자의 경우의 수를 구할 수 있습니다. 또한 아주 기본적인 자바 API만 사용했기 때문에 레벨 1 난이도 문제의 취지에 적합하다고 생각해서 아주 기본적인 자바 문법만 알고 있는 입문자도 구현해낼 수 있는 답안이므로 공유합니다.

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("[ 최소 값에서 최대 값 까지 각 숫자의 각 자릿수에 있는 숫자들의 합을 구합니다. ]");
        System.out.print("최소 값 > ");
        int minNum = scanner.nextInt();
        System.out.print("최대 값 > ");
        int maxNum = scanner.nextInt();
        boolean runner = true;

        int leftNumber;
        int[] countNum = new int[11];

        System.out.println("[ 이하 " + minNum + " ~ " + maxNum + "까지의 각 자리 수의 개수 합 ]");
        for(int start = minNum; start <= maxNum; start++) {
            leftNumber = start;
            while(runner) {
                if(leftNumber >= 10) {
                    countNum[leftNumber % 10 + 1] += 1;
                    leftNumber /= 10;
                } else {
                    countNum[leftNumber % 10 + 1] += 1;
                    break;
                }
            }
        }
        for(int a = 1; a <= 10; a++) {
            if(countNum[a] != 0) {
                System.out.println("숫자 " + (a-1) +" : " + countNum[a] + "개");
            }
        }
        System.out.println("숫자 개수가 0개인 경우 표시되지 않습니다.");
    }
}

2017/04/16 02:39

SungWook Jung

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

using namespace std;

int main( int argc , char** argv )
{
    char    temp[ 24 ];
    int start = 1;
    int end = 1000;

    vector< int > result( 10 , 0 );

    for( int i = start ; i <= end ; ++i )
    {
        snprintf( temp , sizeof( temp ) , "%d" , i );
        for( size_t j = 0 ; j < strlen( temp ) ; ++j )
        {
            result[ temp[ j ] - 48 ]++;
        }
    }

    for( size_t i = 0 ; i < result.size() ; ++i )
    {
        if( result[ i ] > 0 )
        {
            printf( "%d:%d " , i , result[ i ] );
        }
    }
    cout << endl;
}

2017/04/16 12:13

오승석

public static void Main(string[] args)
        {
            //0 ~ 9 자리 카운터
            int[] numArr = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            //0 ~ 1000까지
            for (int i = 0; i <= 1000; i++)
            {
                char[] arr = i.ToString().ToCharArray();
                for (int j = 0; j < arr.Length; j++)
                {
                    numArr[int.Parse(arr[j].ToString())] += 1;
                }
            }
            //개수 출력
            for (int i = 0; i < numArr.Length; i++)
            {
                Console.WriteLine(i + " 의 갯수는 " + numArr[i] + " 이다");
            }
        }

2017/04/18 11:48

Gyuyeol Kyung

def countnum(a,b):
    result=[]
    for i in range(a,b+1):
        if i <10:
            result.append(i)
        if 10<=i<100:
            first1,last1=divmod(i,10)
            result.append(first1)
            result.append(last1)
        if 100<=i<1000:
            first,last=divmod(i,10)
            first1,last1=divmod(first,10)
            result.append(last)
            result.append(first1)
            result.append(last1)
        if i==1000:
            result.append(1)
            result.append(0)
            result.append(0)
            result.append(0)
    for b in range(10):
        final=print("{0}:{1}".format(b,result.count(b)))
    return final

print(countnum(1,1000))

2017/04/18 13:10

조현

class Coding_dj {
    public static void main(String[] args) {
        /*
            예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자

            10 = 1, 0
            11 = 1, 1
            12 = 1, 2
            13 = 1, 3
            14 = 1, 4
            15 = 1, 5

            그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개
        */
        int[] digit_c = Math_Key.digitCnt(1,1000);

        for(int v : digit_c){
            System.out.print(v+" ");
        }
    }
}


class Math_Key {

    static int[] digitCnt(int s, int e){
        int[] arr = new int[10];

        for(int i = s ; i <= e ; i++){
            int temp = i;
            while(temp > 0){
                //System.out.println("!!! "+temp%10);
                arr[temp%10]++;
                temp /= 10;
            }
        }

        return arr;
    }
}

2017/04/19 14:52

SeonKi Lee

python

a = [0,0,0,0,0,0,0,0,0,0]

for i in range(1,1001):
    for j in str(i):
        a[int(j)] += 1

print a

2017/04/20 16:03

김나랑

class 연습3 { public static void main(String[] args) {

/* 예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자

10 = 1, 0 11 = 1, 1 12 = 1, 2 13 = 1, 3 14 = 1, 4 15 = 1, 5

그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개 */ int[] aaa = ukiikii.java(1,1000);

for(int v : aaa) {
    System.out.println(v+" ");
    }
}

} class ukiikii {

static int[] java(int a, int b) {
int arr[] = new int[10];

for(int i=a ; i<=b ; i++) {
    int temp = i;
    while(temp >0) {
        arr[temp%10]++;
        temp /= 10;
        }
    }
    return arr;
}

}

2017/04/21 15:15

Kim Siuk

//자바로 풀어 보았습니다.

import java.util.*;

public class CountNumber{ public static void main(String[] args){ Scanner input=new Scanner(System.in); int[] count = new int[10]; String S;1. 1.

    while(true){
        System.out.print("1~1000사이의 숫자를 입력하시오: ");
        S = input.nextLine();
        int[] temp = counter(S);
        for(int i=0;i<10;i++){
            count[i] = count[i] + temp[i];
        }
        for(int i=0;i<10;i++){
            System.out.print(i+": " +count[i]+"개, ");
        }
        System.out.println();
    }
}
public static int[] counter(String S){
    int numS = S.length();
    int[] sepNum = new int[numS];
    int[] count = new int[10];

    for(int i=0;i<numS;i++){
        sepNum[i] = Character.getNumericValue(S.charAt(i));
    }
    for(int k:sepNum){
        count[k]++;
    }
    return count;

}

}

2017/04/26 01:28

CHIJE PARK

list = [0,0,0,0,0,0,0,0,0,0]

for i in range(1,1001):
    for j in str(i):
        list[int(j)] += 1
print(list)

2017/04/28 00:44

Hyoseop JO

package javaDojang;

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

    int on = 0;
    int two=0; 
    int three =0;
    int fo =0;
    int five=0;
    int six=0; 
    int seven=0; 
    int eight=0;
    int nine =0;

    for (int i = 1; i <=1000; i++) {
        int one = i %10;
        int ten = i / 10 %10;
        int hundred = i/100 % 10;
        int thousand = i/1000;
      System.out.println("-----");
       System.out.println(thousand);
       System.out.println(hundred);
       System.out.println(ten);
       System.out.println(one);

       int[] four = new int[]{one, ten,hundred, thousand};
       for(int j:four){
          switch (j) {
          case 1:
              on++;
              break;
          case 2:
              two++;
              break;
          case 3:
              three++;
              break;
          case 4:
              fo++;
              break;
          case 5:
              five++;
              break;
          case 6:
              six++;
              break;
          case 7:
              seven++;
              break;
          case 8:
              eight++;
              break;
          case 9:
              nine++;
              break;

          }  
       }

    }
    System.out.println("1 ="+on+"개, 2="+two+"개, 3="+three+"개, 4="+fo+"개, 5="+five+"개, 6="+six+"개, 7="+seven+"개, 8="+eight+"개, 9="+nine+"개  ");
}

}

2017/05/01 08:43

Esther Maeng

num_0=0
num_1=0
num_2=0
num_3=0
num_4=0
num_5=0
num_6=0
num_7=0
num_8=0
num_9=0

for i in range(1,1001):
    word = str(i)
    for j in range(len(word)):
        #print(word[j])
        if word[j] == '0' : num_0=num_0+1
        if word[j] == '1' : num_1=num_1+1
        if word[j] == '2' : num_2=num_2+1
        if word[j] == '3' : num_3=num_3+1
        if word[j] == '4' : num_4=num_4+1
        if word[j] == '5' : num_5=num_5+1
        if word[j] == '6' : num_6=num_6+1
        if word[j] == '7' : num_7=num_7+1
        if word[j] == '8' : num_8=num_8+1
        if word[j] == '9' : num_9=num_9+1

print(" 0의 개수는 : %d \n"% num_0)
print(" 1의 개수는 : %d \n"% num_1)
print(" 2의 개수는 : %d \n"% num_2)
print(" 3의 개수는 : %d \n"% num_3)
print(" 4의 개수는 : %d \n"% num_4)
print(" 5의 개수는 : %d \n"% num_5)
print(" 6의 개수는 : %d \n"% num_6)
print(" 7의 개수는 : %d \n"% num_7)
print(" 8의 개수는 : %d \n"% num_8)
print(" 8의 개수는 : %d \n"% num_9)

2017/05/01 21:48

민석인

package codingdojang;

public class P2 {
    public static void main(String[] args) {
        int countNumber[] = new int[1000];
        int from = 1, to = 1000;
        int saveNumber;

        for (int i = 0; i < countNumber.length; i++) {
            countNumber[i] = 0;
        }

        for (int i = from; i <= to; i++) {
            int j = i;
            while (j != 0) {
                saveNumber = j % 10;
                j /= 10;
                countNumber[saveNumber]++;
            }
        }
        for (int i = 0; i < countNumber.length; i++) {
            if (countNumber[i] != 0) {
                System.out.println(i + ":" + countNumber[i]);
            }
        }

    }
}

결과는 이렇게 나왔습니다. 0:192 1:301 2:300 3:300 4:300 5:300 6:300 7:300 8:300 9:300

2017/05/02 13:53

조상현

코딩 초보라서 어렵내요

#include<stdio.h>

int main() {
    int number[] = { 0,0,0,1 };
    int zero_to_nine[] = { 0,0,0,0,0,0,0,0,0,0 };
    int k, i, j, p, q;
    for (i = 0; i < 1000; i++) {
        for (q = 0; q < 4; q++) {
            if (number[q] > 0) {
                break;
            }
        }
        for (j = 3; j >= q; j--) {
            zero_to_nine[number[j]]++;
        }
        number[3]++;
        for (k = 3; k > 0; k--) {
            if (number[k] == 10) {
                number[k - 1]++;
                number[k] = 0;
            }
            else {
                break;
            }
        }
    }
    for (p = 0; p < 10; p++) {
        printf("%d는 %d개 입니다\n", p, zero_to_nine[p]);
    }
    return 0;
}

2017/05/02 14:52

흐니

#declare the number list
n_number = []
#pre-allocation
for i in range(0,10):
    n_number.append(0)
# while 1~9
for i in range(1,10):
    n_number[i]=1
# while 10~99
for i in range(1,10):
    n_number[i]=n_number[i]+10 #MSB
for i in range(0,10):
    n_number[i]=n_number[i]+9 #LSB
# while 100~999
for i in range(1,10):
    n_number[i]=n_number[i]+100 #MSB
for i in range(0,10):
    n_number[i]=n_number[i]+90 #middle number                         
for i in range(0,10):
    n_number[i]=n_number[i]+90 #LSB
# while 1000
n_number[0]=n_number[0]+3
n_number[1]=n_number[1]+1


print(n_number)

2017/05/03 16:11

Proboscis Kita

count={ x:0 for x in range(0,10) }

for x in range(1,1001): for i in str(x): count[int(i)]+=1

print(count)

2017/05/04 18:44

sadjbw

list = []
k= 10

def countnm(arg):
    imsi = arg
    j= 1
    while True:
        if(imsi<pow(k,j)):
                list.append(imsi//pow(k,j-1))
                imsi=i%pow(k,j-1)
                j=j-1
                if(j==0):
                    break
        else:
            j=j+1


for i in range (1,1001):
    countnm(i)

for p in range (0,10):
    nm=list.count(p)
    print(format(p,'d'),"의개수는",format(nm,'d'),"입니다")       

2017/05/05 15:52

한인환

파이썬.3 사용

#make list of numbers
def num_list(x,y):

    numbers = []
    for number in range(x,y+1):
        numbers.append(number)

    return numbers

"""input is a list of numbers. 
output is the number of each single-digit"""

def digit_check(nlist):

    digit_list = [0,0,0,0,0,0,0,0,0,0]

    for number in nlist:

        for digit in str(number):

            add = int(digit)
            digit_list[add] = digit_list[add] + 1

    return digit_list

#get input, print answer
x = int(input("Starting number : "))
y = int(input("Ending number : "))

digit_list = digit_check(num_list(x,y))

for a in range(10):
    print("Number of " + str(a) + " is " + str(digit_list[a]) + ".")

2017/05/05 21:27

정의석

for i in range(10):
    a = str([j for j in range(10, 16)]).count(str(i))
    print(r'{} => {}개'.format(i, a))

2017/05/06 09:30

최경식

#coding=utf-8

count = [0,0,0,0,0,0,0,0,0,0]  # 0부터 9까지의 자리를 리스트로 만듬

for i in range(1, 1001) : # i 변수에 1 ~ 1000까지를 대입하여 반복 실행함

    for j in str(i) : # j 변수에 i값을 문자로 대응시킴 (32 일 경우, j는 3과 2가 대입되어 두번 작업)

        n = int(j)  # j 값을 정수값으로 변환

        count[n] += 1 # 변환된 값의 위치에 1을 더해서 숫자를 카운팅

        #대응된 숫자가 324일 경우, j는 3, 2, 4를 각각 한번 수행하게 되며
        #count의 3, 2, 4에 대응하는 리스트 값에 각각 1을 더해주게 됨됨

print(count)

2017/05/07 21:41

최준호

import collections
a=list()
for i in range(1,1001):
    a+=list(str(i))
    print(collections.Counter(a))

2017/05/09 21:58

빅디펜스

(C언어로 작성)

#include <stdio.h>
void main()
{
    int num[10] = { 0 };
    int digit1, digit2, digit3;

    for (i = 1; i <= 9; i++)
        num[i] += 1;

    for (i = 10; i <= 99; i++)
    {
        digit2 = i / 10;
        digit1 = i - (digit2 * 10);

        for (j = 0; j <= 9; j++)
        {
            if (digit2 == j)
                num[j] += 1;
            if (digit1 == j)
                num[j] += 1;
        }
    }

    for (i = 100; i <= 999; i++)
    {
        digit3 = i / 100;
        digit2 = (i - (digit3 * 100)) / 10;
        digit1 = i - (digit3 * 100) - (digit2 * 10);

        for (j = 0; j <= 9; j++)
        {
            if (digit3 == j)
                num[j] += 1;
            if (digit2 == j)
                num[j] += 1;
            if (digit1 == j)
                num[j] += 1;
        }
    }

    num[1] += 1; num[0] += 3;   // 1000의 각 숫자 더하기

    for (i=0; i<=9; i++)
        printf("%d : %d개\n", i, num[i]);
}

2017/05/13 16:17

강동주


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _CRT_SECURE_NO_WARNING

int main()
{
    int countlist[10] = { 0,0,0,0,0,0,0,0,0,0 };
    char tmp[5];

    for (int i = 1; i <= 1000; i++) {
        itoa(i, tmp, 10);
        for (int j = 0; j < strlen(tmp); j++) {
            switch (tmp[j])
            {
            case '0' :
                countlist[0]++;
                break;
            case '1':
                countlist[1]++;
                break;
            case'2':
                countlist[2]++;
                break;
            case'3':
                countlist[3]++;
                break;
            case '4':
                countlist[4]++;
                break;
            case '5':
                countlist[5]++;
                break;
            case '6':
                countlist[6]++;
                break;
            case '7':
                countlist[7]++;
                break;
            case '8':
                countlist[8]++;
                break;
            case '9':
                countlist[9]++;
                break;
            default: break;
            }
        }
    }
    for (int k = 0; k < (sizeof(countlist) / sizeof(countlist[0])); k++) {
        printf("%d 의 개수는 %d 입니다 \n", k, countlist[k]);
    }
}
  1. 0-9 까지 숫자의 개수를 저장 할 배열 countlist[10] 생성 ( 0-9 까지 숫자의 개수를 저장하기 때문에 10자리 배열 생성)
  2. 정수로부터 변환된 문자열을 저장할 tmp[5] 생성 ( 네자리수 까지 입력 받기 때문에 /0 을 포함하여 5자리 배열 생성)
  3. 1-1000 반복문 실행
  4. 3의 각 시행에 따라 4-1. itoa 를 사용하여 정수를 문자열로 변환 4-2. 문자열의 길이만큼 반복문 실행 4-3 4-2 의 각 시행에 따라 4-3-1. switch 를 사용하여 해당 정수가 문자열에 포함될 경우 countlist[10] 의 element 를 1증가 4-3-2. default 는 pass
  5. 반복문이 완료되면 countlist[10] 을 출력

2017/05/15 10:58

백승현

import operator

def check(startIdx, endIdx):
    dictionary = {}

    for i in range(startIdx, endIdx + 1):
        for j in str(i):
            try:
                dictionary[j] = dictionary[j] + 1
            except:
                dictionary[j] = 1

    return dictionary


startIdx = 1
endIdx = 1000
result = check(startIdx, endIdx)
sortResult = sorted(result.items(), key=operator.itemgetter(0))

print(sortResult)

2017/05/15 16:15

김동민

a = list(range(1,1001))
b = list(range(0,10))
c = 0
for n in list(b):
    n = str(n)
    for i in list(a):
        b = str(a[i-1])
        c = c + b.count(n)

    print ("{0} : {1}" .format(n, c))
    c = 0

2017/05/15 16:26

Bo Hyun Seo

count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


def number_counting(m, n):
    string = str(list(range(m, n+1)))
    for character in string:
        if character.isnumeric() is True:
            count[int(character)] += 1
    return count


print(number_counting(1, 1000))

2017/05/16 10:45

Taewon Song

#include<stdio.h>
int down(int a, int b)
{
    return (int)((double)a / (double)b);;
}
int pow(int num)
{
    int i = 0;
    int result = 1;
    if (num == 0) return 1;
    for (i = 0; i < num; i++)
    {
        result = result * 10;
    }
    return result;
}
void count_in_1st(int num, int*count)
{
    if (num == 0)count[0]++;
    else if (num == 1)count[1]++;
    else if (num == 2)count[2]++;
    else if (num == 3)count[3]++;
    else if (num == 4)count[4]++;
    else if (num == 5)count[5]++;
    else if (num == 6)count[6]++;
    else if (num == 7)count[7]++;
    else if (num == 8)count[8]++;
    else count[9]++;
}
void count_num(int num,int iteration, int* count)
{
    int i =0;
    int num_1 = 0;
    int loop = iteration;
    for (i = 0; i < loop; i++)
    {
        num_1 = down(num, pow(iteration));
        count_in_1st(num_1, count);
        num = num - (num_1*pow(iteration));
        iteration--;
    }
    count_in_1st(num, count);
}

int main()
{
    int num[] = { 0};
    int iteration = 0;
    int count[10] = {0};

    for (int i = 0; i < 1000; i++)
    {
        num[i] = i+1;
        if (0 <= num[i]&num[i] < 10)
        {
            iteration = 0;
            count_num(num[i], iteration, count);
        }
        else if (10 <= num[i]&num[i] < 99)
        {
            iteration = 1;
            count_num(num[i], iteration, count);
        }
        else if (100 <= num[i]&num[i] < 999)
        {
            iteration = 2;
            count_num(num[i], iteration, count);
        }
        else if (1000 <= num[i]&num[i] < 9999)
        {
            iteration = 3;
            count_num(num[i], iteration, count);
        }

    }
    int i = 0;
    for (i = 0; i < 10; i++)
        printf("%d의 숫자는 : %d번 나왔다\n", i, count[i]);




}

2017/05/17 01:39

박장선

class numofnum:
    def __init__(self, n):
        self.n = n

    def seperator(self, i):
        return [ s  for s in str(i) ]

    def counting(self):
        count = { str(i):0 for i in range(10) }
        for i in range(1, self.n+1):
            for s in self.seperator(i):
                count[s] += 1
        return count
``````{.python}
a = numofnum(100000)

a.counting()

{'0': 38894, '1': 50001, '2': 50000, '3': 50000, '4': 50000, '5': 50000, '6': 50000, '7': 50000, '8': 50000, '9': 50000}

2017/05/21 18:15

겨털에뽀뽀

        String intToString;
        String number[];
        int count[] = new int[10];
        int startNum = 1;
        int lastNum = 1000;

        for(int i = startNum; i < lastNum + 1; i++) {
            intToString = i + "";
            number = intToString.split("");
            for(int j = 0; j < number.length; j++) {
                for(int k = 0; k < 10; k++) {
                    if(Integer.parseInt(number[j]) == k) {
                        count[k]++;
                    }
                }
            }
        }

        System.out.println("1 ~ 1000에서 각 숫자의 개수 구하기");
        System.out.println("0 : " + count[0] + "개");
        System.out.println("1 : " + count[1] + "개");
        System.out.println("2 : " + count[2] + "개");
        System.out.println("3 : " + count[3] + "개");
        System.out.println("4 : " + count[4] + "개");
        System.out.println("5 : " + count[5] + "개");
        System.out.println("6 : " + count[6] + "개");
        System.out.println("7 : " + count[7] + "개");
        System.out.println("8 : " + count[8] + "개");
        System.out.println("9 : " + count[9] + "개");

2017/05/22 13:09

2mlover

package codingstudio;

public class Q105 {

    public static void main(String[] args) {
        System.out.println("----- 코딩도장 105번 문제 풀이 -----");

        System.out.println("1~1000에서 각 숫자의 개수 구하기");

        // 선언부
        int[] answer = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        String conv;
        char[] ca = null;

        int max = 1000;

        for (int i = 1; i <= max; i++) {
            System.out.println(i + " 숫자 분할");

            conv = Integer.toString(i);
            ca = conv.toCharArray();

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



                System.out.println(ca[j]);
                int calc = (int) ca[j] - 48;

                answer[calc]++;

            }

        }

        // 정답 출력

        for (int i = 0; i < answer.length; i++) {
            System.out.println(i + " 는 " + answer[i] + " 개 있습니다.");
        }

    }

}

2017/05/25 14:53

DrKilling

a = [0 for i in range(10)]
for i in range(1,1001):
    for j in str(i):
        a[int(j)] += 1
print(a)

------------------------------------

a = [0 for i in range(10)]
j = 1
for i in range(1,1001):
    while j != i+1:
        for k in range(len(str(j))):
            a[int(str(j)[k])] += 1
        j += 1
print(a)

두 가지의 풀이입니다.

2017/05/26 20:45

S ReolSt

C로 작성했습니다.

#include<stdio.h>

int main()
{
    int min, max, count, backup;
    int numcount[10] = { 0 }; //(각 배열 인덱스 번호를 각 숫자의 카운트 공간으로 활용)

    printf("낮은값을 입력하세요 : ");
    scanf("%d", &min);
    printf("높은값을 입력하세요 : ");
    scanf("%d", &max);          // 10~1000이라 하였으나 다른 수도 가능하게 입력 받도록 하였습니다.  

    count = min;
    backup = min;

    while(count<=max)
 // for(backup=min; backup<=max; backup++)을 사용하니 continue때마다 증감식(backup++) 작동돼서 while문 사용
    {       
        numcount[count % 10]++; // 제일 끝자리수 카운트 
        if (count >= 10) //10자리 이상이면
        {
            count /= 10; //끝자리 삭제과정 (예 : 325 -> 5 카운트 하였으므로  5삭제후 32만듬) 
            continue;    // 남은수 카운트 위해 돌아감
        }
        backup++;
        count = backup; //첫 자리만 남았으므로 복원해줍니다. 
    }

    for (int i = 0; i < 10; i++)
    {
        printf("%d의 갯수 : %d\n", i, numcount[i]); //출력
    }

    return 0;
}

2017/05/27 12:32

김우주

C-Sharp

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<char, int> count = new Dictionary<char, int>();

        for (int num = 1; num <= 1000; num++)
        {
            foreach (char c in num.ToString())
            {
                if (count.TryGetValue(c, out int value))
                    count[c]++;
                else
                    count.Add(c, 1);
            }
        }

        foreach (KeyValuePair<char, int> kvp in count)
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
    }
}

2017/05/30 11:47

디디

public static void main(String[] args) { int n0=0, n1=1, n2=1, n3=1, n4=1, n5=1, n6=1, n7=1, n8=1, n9=1 ;

    for(int i=10; i<=1000; i++){
        if(i<100){
            String j = Integer.toString(i);
            char c0=j.charAt(0);
            char c1=j.charAt(1);
            int num0 = Integer.parseInt(Character.toString(c0));
            int num1 = Integer.parseInt(Character.toString(c1));

            switch(num0){
            case 0: n0++; break;
            case 1: n1++; break;
            case 2: n2++; break;
            case 3: n3++; break;
            case 4: n4++; break;
            case 5: n5++; break;
            case 6: n6++; break;
            case 7: n7++; break;
            case 8: n8++; break;
            case 9: n9++; break;
            }
            switch(num1){
            case 0: n0++; break;
            case 1: n1++; break;
            case 2: n2++; break;
            case 3: n3++; break;
            case 4: n4++; break;
            case 5: n5++; break;
            case 6: n6++; break;
            case 7: n7++; break;
            case 8: n8++; break;
            case 9: n9++; break;
            }
        }else{
            String j = Integer.toString(i);
            char c0=j.charAt(0);
            char c1=j.charAt(1);
            char c2=j.charAt(2);
            int num0 = Integer.parseInt(Character.toString(c0));
            int num1 = Integer.parseInt(Character.toString(c1));
            int num2 = Integer.parseInt(Character.toString(c2));

            switch(num0){
            case 0: n0++; break;
            case 1: n1++; break;
            case 2: n2++; break;
            case 3: n3++; break;
            case 4: n4++; break;
            case 5: n5++; break;
            case 6: n6++; break;
            case 7: n7++; break;
            case 8: n8++; break;
            case 9: n9++; break;
            }
            switch(num1){
            case 0: n0++; break;
            case 1: n1++; break;
            case 2: n2++; break;
            case 3: n3++; break;
            case 4: n4++; break;
            case 5: n5++; break;
            case 6: n6++; break;
            case 7: n7++; break;
            case 8: n8++; break;
            case 9: n9++; break;
            }
            switch(num2){
            case 0: n0++; break;
            case 1: n1++; break;
            case 2: n2++; break;
            case 3: n3++; break;
            case 4: n4++; break;
            case 5: n5++; break;
            case 6: n6++; break;
            case 7: n7++; break;
            case 8: n8++; break;
            case 9: n9++; break;
            }
        }
    }//for
    System.out.println(n0);
    System.out.println(n1);
    System.out.println(n2);
    System.out.println(n3);
    System.out.println(n4);
    System.out.println(n5);
    System.out.println(n6);
    System.out.println(n7);
    System.out.println(n8);
    System.out.println(n9);
}

2017/05/30 14:29

강혜지

c로 작성

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

    for(i=1;i<=1000;i++) for(j=1;j<=1000;j*=10) if(i>=j) num[(i/j)%10]++;
    for(i=0;i<10;i++) printf("%d : %d개\n",i,num[i]);

    return 0;
}

2017/05/31 09:51

박동준

def sum_string(first_string, last_string) :
    initial_string = ""
    for i in range(int(first_string),int(last_string)+1) :
        initial_string = initial_string + str(i)
    result = initial_string
    return result           # result type => str

def count_string(string) :
    dummy = []
    for i in range(0,10) :
        dummy.append(string.count(str(i)))
    result = dummy
    return result            # result type => list

initial_list = []
for i in range(0,10) :
    key = str(i)
    value = count_string(sum_string('10','15'))[i]
    print('%s : %d' % (key, value))

2017/05/31 17:10

L

public class NumCount2 {
    public static void main(String[] args) {
        // 배열을 쓴다면
        int n[] = new int[10];
        // 개수구하기
        for(int i=10;i<=15;i++)
            for(int t=i;t>0;t/=10) n[t%10]++;
        // 출력하기
        for(int i=0;i<n.length;i++)
            System.out.println(i+"의 개수 : " + n[i]);
    }
}

2017/06/02 16:50

김중운

import java.util.Scanner;

/* * 완전수 구하기 * 자기 자신을 제외한 모든 양의 약수들의 합이 자기 자신이 되는 자연수를 완전수라고 한다. * 예를 들면, 6과 28은 완전수이다. 6=1+2+3 // 1,2,3은 각각 6의 약수 // 자연수 N을 받고, 출력으로 N 이하의 모든 완전수를 출력하는 코드를 작성하라. * / public class Alogrism_Test1 {

public static void main(String[] args) {

    int num = 0;

    Scanner scan = new Scanner(System.in);
    System.out.println(" 자연수 입력 ");
    num = scan.nextInt();
    System.out.print(num+" 이하의 완전수는 ? ");
    for(int i=1; i<=num; i++){
        if(isPerfect(i)){
            System.out.print(i+", ");
        }
    }
}


public static boolean isPerfect(int num){
    int sum=0;

    for(int i=1; i<=num; i++){
        if(num%i==0 && num!=i){
            sum+=i;
        }
    }if(sum==num){
        return true;
    }
    return false;
}

}

import java.util.Scanner;

/**
 *  완전수 구하기 
 *  자기 자신을 제외한 모든 양의 약수들의 합이 자기 자신이 되는 자연수를 완전수라고 한다. 
 *  예를 들면, 6과 28은 완전수이다. 6=1+2+3 // 1,2,3은 각각 6의 약수 // 자연수 N을 받고, 출력으로 N 이하의 모든 완전수를 출력하는 코드를 작성하라.
 * */
public class Alogrism_Test1 {

    public static void main(String[] args) {

        int num = 0;

        Scanner scan = new Scanner(System.in);
        System.out.println(" 자연수 입력 ");
        num = scan.nextInt();
        System.out.print(num+" 이하의 완전수는 ? ");
        for(int i=1; i<=num; i++){
            if(isPerfect(i)){
                System.out.print(i+", ");
            }
        }
    }


    public static boolean isPerfect(int num){
        int sum=0;

        for(int i=1; i<=num; i++){
            if(num%i==0 && num!=i){
                sum+=i;
            }
        }if(sum==num){
            return true;
        }
        return false;
    }
}

2017/06/03 14:00

93D

var su = 1;
var array = [0,0,0,0,0,0,0,0,0,0];

var count = (first,end) => {
    for(first; first <= end; first++){
        while(first){
            if(su > first){
                su = 1;
                break;
            }
            su = su*10;
            var a = ( (((first % su)+'').charAt(0))*1 );
            switch(a){
                case a : array[a]+=1; break;
            }  
        }   
    }

    return array;
}

//         count(처음값,마지막값)
console.log(count(1,30));

2017/06/11 13:50

redshark

public class Test2 {

    public static void main(String[] args) {

        int[] n = new int[10];

        for(int i=1; i<=1000; i++) {
            n[i%10]++;
            if(i>=10) n[(i/10)%10]++;
            if(i>=100) n[(i/100)%10]++;
            if(i==1000) n[1]++;
        }

        for(int i=0; i<10; i++) {
            System.out.println(i+"의 갯수 : "+n[i]+" 개");
        }

    }

}

2017/06/12 17:14

허수진

s_list = list()
p_list = [0,0,0,0,0,0,0,0,0,0]

def numcount(startnum, endnum):
    num = startnum
    while num > 0:
        s_list.append(int(str(num)[-1]))
        num = num // 10

    print (s_list)

    for i in range(startnum, endnum + 1):
        for j in range(s_list.__len__()):
            p_list[s_list[j]] += 1

        for j in range(s_list.__len__()):
            s_list[j] +=  1
            if (s_list[j] > 9):
                s_list[j] = 0
                if (j == s_list.__len__() - 1):
                   s_list.append(1)
            else:
                break;

    for i in range(10):
        print ("[ "+str(i)+" ] : "+ str(p_list[i]) +" 개")


def main():
    numcount(1,1000)

if __name__ == '__main__' :
    main()


2017/06/13 00:14

KangHyun Lee

a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
x = 1

def count(u):
    a[0] = a[0] + str(u).count('0')
    a[1] = a[1] + str(u).count('1')
    a[2] = a[2] + str(u).count('2')
    a[3] = a[3] + str(u).count('3')
    a[4] = a[4] + str(u).count('4')
    a[5] = a[5] + str(u).count('5')
    a[6] = a[6] + str(u).count('6')
    a[7] = a[7] + str(u).count('7')
    a[8] = a[8] + str(u).count('8')
    a[9] = a[9] + str(u).count('9')


while x <= 1000:
    count(x)
    x += 1


print('''
    '0의 개수' = %d
    '1의 개수' = %d
    '2의 개수' = %d
    '3의 개수' = %d
    '4의 개수' = %d
    '5의 개수' = %d
    '6의 개수' = %d
    '7의 개수' = %d
    '8의 개수' = %d
    '9의 개수' = %d''' %(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9]))

def로 함수 만드는 부분에서 while문 돌리면 되려 속도가 엄청 느려지던데 이유 아시는분?

2017/06/17 17:25

TohnoSiki

javascript

var counts = [];

for (let i = 1; i <= 1000; i++) {
    Array.from(`${i}`).map(v => counts[v] = (counts[v] || 0) + 1);
}

console.log(counts.map((v, i) => `${i}:${v}개`).join(", "));

2017/06/18 03:18

funnystyle

def get_num_count(start_num, end_num):
    num_cnt_dict = dict(zip(range(10), [0]*10))
    for i in range(start_num, end_num + 1):
        num_uniq = [x for x in str(i)]
        for x in str(i):
            num_cnt_dict[x] += 1

    return num_cnt_dict

get_num_count(10, 15) 결과 : {0: 1, 1: 7, 2: 1, 3: 1, 4: 1, 5: 1, 6: 0, 7: 0, 8: 0, 9: 0}

2017/06/18 19:41

devin

public static void main(String[] args){ int[] count = new int[10]; int start = 1; int end = 100; System.out.println(start + " ~ " + end + "의 0 ~ 9 숫자 개수"); for(int i = start ; i <= end; i++){ int t = i; while(t > 0){ int r = t % 10; switch(r){ case 0 : count[r]++; break; case 1 : count[r]++; break; case 2 : count[r]++; break; case 3 : count[r]++; break; case 4 : count[r]++; break; case 5 : count[r]++; break; case 6 : count[r]++; break; case 7 : count[r]++; break; case 8 : count[r]++; break; case 9 : count[r]++; break; } t /= 10; } }

    for(int i = 0; i < count.length; i++){
        System.out.println(i + "의 개수 = " + count[i]);
    }
}

2017/06/19 09:17

김대원

        int[] sc = new int[10];
        for (int i = 1; i <= 1000; i++) {
            String num = Integer.toString(i);
            int size = num.length();
            for (int j = 0; j <= size - 1; j++) {
                int k = num.charAt(j) - '0';
                sc[k] = sc[k] + 1;
            }
        }
        for (int i = 0; i < 10; i++)
            System.out.println(i + " : " + sc[i]);

자바....

2017/06/20 11:54

이한솔

list = []
for i in range (1, 1001):
    for n in str(i):
        list.append(n)

for p in range(0,10):
    print(p, list.count(str(p)))

2017/06/26 21:04

권용규

cnt = {str(x):0 for x in range(10)}

for n in range(1, 1001):
    for d in str(n):
        cnt[d] += 1

print(cnt)

2017/07/03 13:06

Noname

Python으로 단순하게 풀었습니다. 0~9 까지를 key로 갖는 dictionary를 하나 정의해두고, 각 자리수마다 1씩 더해주도록 했습니다.

def solve(start, end):
    counts = {x: 0 for x in range(0, 10)}

    for x in range(start, end + 1):
        while x > 0:
            counts[x % 10] += 1
            x = int(x / 10)

    return [item for item in counts.items() if item[1] is not 0]

print(solve(10, 15))
print(solve(1, 1000))

[(0, 1), (1, 7), (2, 1), (3, 1), (4, 1), (5, 1)] [(0, 192), (1, 301), (2, 300), (3, 300), (4, 300), (5, 300), (6, 300), (7, 300), (8, 300), (9, 300)] 결과는 위처럼 0은 192개, 1은 301개, 나머지는 300개씩 나옵니다.

2017/07/03 13:15

SOUP

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

int main()
{
    string str_num[1000];
    int result[10] = {0, };

    for (int i = 1; i <= 1000; i++) {
        str_num[i-1] = to_string(i);

        for (int j = 0; j < str_num[i-1].length(); j++) {
            int index = str_num[i-1].at(j) - '0';
            result[index] += 1;
        }
    }

    for (int i = 0; i < 10; i++) {
        std::cout <<result[i]  << std::endl;
    }
}

2017/07/03 14:05

Logan

public class Ex005 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] count = new int[10];
        for(int i = 1; i <= 1000; i++) {
            for(int soloNum = i; soloNum > 0; soloNum/=10) {
                int modulo = soloNum % 10;
                count[modulo]++;
            }
        }

        for(int i = 0; i < count.length; i++) {
            System.out.println(i+"의 개수: " + count[i]);
        }
    }

}

0의 개수: 192

1의 개수: 301

2의 개수: 300

3의 개수: 300

4의 개수: 300

5의 개수: 300

6의 개수: 300

7의 개수: 300

8의 개수: 300

9의 개수: 300

2017/07/04 13:11

pg


``````{.python}
d = {}

for i in range(1,1001):

    for j in str(i):

        if d.get(j) == None:
            d[int(j)] = 1  # dic 의 key 값을 int로 하면 자동 정렬 됨
        else:
            d[int(j)] = d[j] + 1

print d.items()

2017/07/05 13:23

강동인

def digit_count(start, end):
    count_arr = [0] * 10             # 0 ~ 9
    for i in range(start, end + 1):
        q = i
        while(1):
            q, r = divmod(q, 10)
            count_arr[r] += 1
            if q == 0:
                break;
    return count_arr

2017/07/07 11:48

이정환

public class Ex5 {
    private static final int BEGIN = 10;
    private static final int END = 15;

    private static int[] result = new int[10];

    public static void main(String[] args) {
        for ( int i = BEGIN; i <= END; i++ ){
            for ( int j = i; j > 0; j /= 10 ){
                 result[j % 10]++;
            }
        }

        //확인
        for ( int i = 0 ; i < result.length;  i++){
            if(result[i] > 0) System.out.println(i + ":"+result[i]+"개");
        }
    }
}

2017/07/07 11:50

요지

package java_tutorial;

public class CountNum {

    public static void main(String[] args) {

        int []count = new int[11];

        for(int i = 1; i < 1001; i++)
        {
                if(i/10==0)
                {
                    count[i]++;
                }
                else if (i/100==0)
                {
                    count[i%10]++;
                    count[i/10]++;
                }
                else if (i/1000==0)
                {
                    count[i%10]++;
                    count[(i/10)%10]++;
                    count[i/100]++;
                }
                else if(i/10000==0)
                {
                    count[i%10]++;
                    count[(i/10)%10]++;
                    count[(i/100)%10]++;
                    count[i/1000]++;
                }
        }

        for(int i = 0; i <10; i++)
        {
                System.out.println(i + "은 " + count[i] + "개 입니다.");
        }
    }

}

2017/07/17 12:02

최원석

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

void total();

int main()
{
    total();
    return 0;
}

void total()
{
    int total[11] = { 0 };
    char tmp[5];
    int i, j;

    for (i = 1; i <= 1000; i++) {
        sprintf(tmp, "%d", i);
        for (j = 0; j < strlen(tmp); j++)
            total[tmp[j] - '0']++;
    }

    for (i = 0; i <= 9; i++) {
        printf("%d : %d개 ", i, total[i]);
    }
    printf("\n");
}

2017/07/20 13:54

정동건

from collections import Counter as C
a = C()
for n in range(0, 1001):
    a += C(list(str(n)))
print(a)

2017/07/22 15:44

이재희

#include <stdio.h>
#define MIN 1
#define MAX 1000

void SetCount(int, int*);

int main()
{
    int i;
    int cnt[10] = { 0, };

    for (i = MIN; i <= MAX; i++)
    {
        SetCount(i, cnt);
    }

    for (i = 0; i < 10; i++)
    {
        printf("%d : %d\n", i, cnt[i]);
    }

    return 0;
}

void SetCount(int input, int* arrInput)
{
    arrInput[input % 10]++;

    if (input > 0)
    {
        SetCount(input / 10, arrInput);
    }

}

재귀를 이용함. 1부터 1000까지 훑으며 각각의 수를 카운트 업.

2017/07/23 20:02

스봉

n = 1 a = 0 b = 0 c = 0 d = 0 e = 0 f = 0 g = 0 h = 0 i = 0 j = 0

while n <= 1000 : num = "%d" %n a = a + num.count('0') b = b + num.count('1') c = c + num.count('2') d = d + num.count('3') e = e + num.count('4') f = f + num.count('5') g = g + num.count('6') h = h + num.count('7') i = i + num.count('8') j = j + num.count('9') n = n + 1

print (" 0"," 1"," 2"," 3"," 4"," 5"," 6"," 7"," 8"," 9")

print (a,b,c,d,e,f,g,h,i,j)

2017/07/23 22:11

Dong Ju Jang

numbers = str(list(range(1, 1001)))
for i in range(0, 10) :
    print("From 1 to 1000, There are", numbers.count(str(i)), i, "s")

2017/07/26 22:44

다크엔젤

import java.util.*;

public class NumberCount {

    public static int[] counter(int n,int[] cnt) {
        cnt[n%10]++;
        if(n/10 != 0) counter(n/10,cnt);
        return cnt;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int start = sc.nextInt();
        int end = sc.nextInt();
        int[] count = new int[10];

        for(int i=start;i<=end;i++) count = counter(i,count);
        for(int i=0;i<10;i++) System.out.println(i+" : "+count[i]);
    }
}

2017/07/29 11:30

곽철이

st_n=input('시작할 숫자를 입력:')
end_n=input('마지막 숫자를 입력:')
result={x:0 for x in range(0,10)}
for i in range(int(st_n),int(end_n)+1):
    num=str(i)
    for j in num:
        result[int(j)]+=1
print(result)

2017/08/01 01:28

Jung Daehyun

Python 작성

Q = [10, 11, 12, 13, 14, 15]
A = [0] * 10

for word in Q:
    word = str(word)
    for i in word:
        i = int(i)
        A[i]+=1

2017/08/01 09:30

arloe

R로 작성했습니다.

Q <- c(10, 11, 12, 13, 14, 15)
CountNum <- function(Q){
  Q <- as.character(Q)
  Q <- strsplit(Q, split = '')
  Q <- do.call('c', Q)
  return(table(count = Q))
}
CountNum(Q)

2017/08/01 09:54

arloe

number_list = [0]*10
for a in range(1,1001):
    aa = [int(i) for i in str(a)]

    for j in aa:
        number_list[j] += 1
counting = [(number,counts) for number,counts in enumerate(number_list)]
for i in range(len(counting)):
    print(counting[i][0],"의 갯수는",counting[i][1],"입니다")

2017/08/04 14:16

이현우

C로 풀었습니다.

#include <stdio.h>
main() {
    int i, share, remain;
    int result[] = { 0,0,0,0,0,0,0,0,0,0 };
    int number[] = { 0,1,2,3,4,5,6,7,8,9 };
    for (i = 1; i<1001; i++) {
        share = i;
        while (share>0) {
            remain = share % 10;
            result[remain] += 1;
            share = share / 10;
        }
    }

    for (i = 0; i<10; i++)
        printf("%d : %d \n", i, result[i]);

    system("pause");
}

2017/08/05 10:23

이자룡

public static Map<Integer, Integer> getNumberCnt() {

        Map<Integer,Integer> map = new HashMap<Integer,Integer>();

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

            String num = String.valueOf(i);
            for(int n=0; n<num.length(); n++) {
                int no = Integer.parseInt(num.substring(n, n+1));

                if(map.get(no) != null) {
                    int cnt = map.get(no);
                    map.put(no, cnt+1);
                }else {
                    map.put(no, 1);
                }
            }
        }

        return map;
    }

    public static void main(String[] args) {
        System.out.println(getNumberCnt());
    }

2017/08/05 17:36

jaehun song

파이썬 초보자 입니다.

x = [0 for x in range(10)]

for i in range(1,1001):
    for j in str(i):
        x[int(j)] += 1
print(x)

2017/08/08 22:16

semipooh

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){

    char arr1[] = {'0','1','2','3','4','5','6','7','8','9'};
    int arr2[] = {0,0,0,0,0,0,0,0,0,0};
    char* tmp=(char*)malloc(sizeof(char)*4);
    for(int i=1;i<=1000;i++)
    {
        sprintf(tmp,"%d",i);
        //printf("%s\n",tmp);   
        for(int j=0;j<strlen(tmp);j++)
        {
            for(int k=0;k<10;k++)
            {
                if(tmp[j]==arr1[k])
                {
                    arr2[k] = arr2[k] + 1;
                }
            }
        }   
    }

    for(int i=0;i<10;i++)
        printf("%d's : %d\n",i,arr2[i]);



}

2017/08/09 09:35

임꺽정

public class Main {
    public static void main(String[] args) {
        int [] cnt = new int[10];   // 0부터 9까지의 개수를 담을 int배열

        for (int i=1; i<=1000; i++) {
            if (i > 0) {        // 1의 자리 추출
                cnt[i%10]++;
            }
            if (i >= 10) {      // 10의 자리 추출
                cnt[i/10%10]++;
            }
            if (i >= 100) { // 100의 자리 추출
                cnt[i/100%10]++;
            }
            if (i == 1000) {    // 1000의 자리 추출
                cnt[i/1000%10]++;
            }
        }

        for (int i=0; i<10; i++) {
            System.out.println(i + "의 개수 : " + cnt[i]);
        }
    }
}

2017/08/14 23:14

임주성

파이썬의 사전(dict)을 사용해 봤습니다.


data=range(1,1001)

result={}


for n in data:
    num=str(n)
    count=0

    for i in range(len(num)):

        try:
            count=result[num[i]]+1
        except KeyError:
            count=1

        result.update({num[i]:count})

print(result)

2017/08/21 13:41

iamm00n

temp=[0,0,0,0,0,0,0,0,0,0]
for i in range (0,1001):
    size=str(i)
    for k in size:
        temp[int(k)]+=1

for m in range (0,10):
    print("%d:%d개"%(m,temp[m]), end=" ")

결과값:0:193개 1:301개 2:300개 3:300개 4:300개 5:300개 6:300개 7:300개 8:300개 9:300개

2017/08/24 21:19

박준

def getCnt(num1, num2):
    arr = ''.join(map(str, range(num1,num2+1)))
    for i in map(str,range(0,10)):
        if arr.count(i) > 0:
            print(i, ':', arr.count(i),'개')

getCnt(10, 15)

2017/08/25 14:04

piko

JAVA

    public static void main(String[] arg) {
        String str = "";
        char[] cList = null;
        int len = 0;
        int n = 0;
        int[] sumList = new int[10];

        for(int i = 1; i <= 1000; i ++) {
            str += Integer.toString(i);
        }

        cList = str.toCharArray();
        len = cList.length;

        for(int j = 0; j < 10; j++) {
            for(int i = 0; i < len; i++) {
                n = Integer.parseInt(String.valueOf(cList[i]));

                if(n == j) {
                    ++sumList[j];
                }
            }

            System.out.println(j + ": " + sumList[j] + "개");
        }
    }

2017/08/28 17:23

androot

// golang 1.9
package main

import (
    "fmt"
    "strconv"
)

func main() {
    count := make([]int, 10) // 각 숫자의 개수가 저장될 슬라이스
    for i := 1; i <= 1000; i++ {
        cnvStr := fmt.Sprintf("%d", i)
        for j := 0; j < len(cnvStr); j++ { // 정수->문자에 대해 자리수별 카운트
            index, _ := strconv.Atoi(cnvStr[j : j+1])
            count[index]++
        }
    }
    // result
    for idx, val := range count {
        fmt.Printf("%d:%3d\n", idx, val)
    }
}

2017/08/29 09:40

mohenjo

numlist=[0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    for k in str(i):
        numlist[int(k)]+=1
for i in range(0,9):
    print(str(i)+':'+str(numlist[i]))


2017/08/30 04:55

impri

public class Example105 {

    public static void main(String[] args) {
        int[] arr = new int[10];

        for (int i = 1; i <= 1000; i++) {
            for (char c : String.valueOf(i).toCharArray()) {
                arr[Character.getNumericValue(c)] += 1;
            }
        }

        for (int i = 0; i < 10; i++) {
            if(arr[i] != 0)
            System.out.println(i + ":" + arr[i]);
        }
    }
}

2017/08/30 12:37

흑돼지

swift

var result = Array(repeating: 0, count: 10)

func main(start n:Int, end m:Int){
    for var num in n...m {
        while num != 0 {
            var s = num % 10
            result[s] += 1
            num = num / 10
        }
    }
    printResult()
}

func printResult(){
    var resultString = ""

    for index in 0..<result.count {
        if (result[index] > 0){
            resultString += String(index) + ":" +  String(result[index])
            resultString += " "
        }
    }
    print(resultString)
}

2017/08/31 18:05

YoungHee Jang

# python 3.6
# 각 숫자의 표시 횟수만큼 더해서 0개 이상인 경우 출력
for i in range(10):
    rst = sum([x.count(str(i)) for x in map(str, range(1, 1001))])
    if rst > 0:
        print("%d: %d" % (i, rst))

# ans:
# 0: 192
# 1: 301
# 2: 300
# 3: 300
# 4: 300
# 5: 300
# 6: 300
# 7: 300
# 8: 300
# 9: 300

2017/09/04 12:05

mohenjo

public class Ex5 {
    public static void main(String[] args) {
        int[] count = new int[10];

        for(int i=1;i<1000;i++) {
            String str = String.valueOf(i);
            for(int k=0;k<str.length();k++) {
                int n = Integer.parseInt(String.valueOf(str.charAt(k)));
                ++count[n];
            }
        }

        for(int i=0;i<count.length;i++) {
            if(count[i] == 0) continue;
            System.out.println(i + ":" + count[i] + "개");
        }
    }
}

0:189개 1:300개 2:300개 3:300개 4:300개 5:300개 6:300개 7:300개 8:300개 9:300개

2017/09/05 17:31

염현우

10 ~ 15 고정된 수를 예로 구하지 않고 Scan 라이브러리를 이용해서 10 ~ 99 자연수 범위 내에서 원하는 숫자들을 전부 셀 수 있는 코드입니다.

import java.util.*;
@SuppressWarnings("unused")
public class individualNum {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int[] numList = new int[10];
        int startCountNum; int endCountNum; 

        /*
         * 예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자

            10 = 1, 0
            11 = 1, 1
            12 = 1, 2
            13 = 1, 3
            14 = 1, 4
            15 = 1, 5

            그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개

            10 ~ 15 고정된 수를 예로 구하지 않고 Scan 라이브러리를 이용해서 10 ~ 99 자연수 범위 내에서 원하는 숫자들을 전부 셀 수 있는 코드입니다.
         */
        System.out.println("(10 ~ 99)");
        System.out.print("plz input ECN > ");
        endCountNum = scan.nextInt();
        System.out.print("plz input SCN > ");
        for(startCountNum = scan.nextInt(); startCountNum <= endCountNum; startCountNum++) {
            int firstNum = (startCountNum / 10); int secondNum = (startCountNum % 10);
            for(int i = 0; i <= 9; i++) {
                if(firstNum == i) {
                    numList[i] += 1;
                }
                if(secondNum == i) {
                    numList[i] += 1;
                }
            }
        }
        for(int x = 0; x <= 9; x++) {
            System.out.println(x +" : " +numList[x]);
        }
    }
}

2017/09/13 15:48

SungWook Jung

dic = {}
for n in range(1, 1001):
    strTemp = str(n)
    for i in range(len(strTemp)):
        v = int(strTemp[i]) 
        if v in dic:
            dic[v] = dic[v] + 1
        else:
            dic[v] = 1

print(dic)


2017/09/29 16:39

thanatoz

def count(a,b):
    result=[0,0,0,0,0,0,0,0,0,0]
    for i in range(a, b + 1):
        string = str(i)
        for j in string:
            result[int(j)] += 1
    for i in range(10):
        print(i, ":", result[i], "개")

count(1,1000)

0 : 192 개 1 : 301 개 2 : 300 개 3 : 300 개 4 : 300 개 5 : 300 개 6 : 300 개 7 : 300 개 8 : 300 개 9 : 300 개

2017/10/26 01:09

명혜미

public class NumberCounting {
    public static void main(String[] args) {
        int[] cntNum = {0,0,0,0,0,0,0,0,0,0};

        for(int i = 0; i < 10; i++){
            for(int j = 0; j < 10; j++){
                for(int k =0; k< 10; k++){
                    if(i != 0) cntNum[i]++;
                    if(i != 0 || j!=0)  cntNum[j]++;
                    cntNum[k]++;
                    //System.out.println(i + "/" + j + "/" + k + " / " + Arrays.toString(cntNum));
                }
            }
        }cntNum[1]++;cntNum[0]+=2;

        System.out.println(Arrays.toString(cntNum));
    }
}

0 ~ 999 까지 세고 수동으로;;

2017/10/27 19:58

Yongjun Kim

초보입니다..;

s2=[]
for i in range(1,1001):
    s1 = list(str(i))
    s2 += s1

for x in range(0,10):
    s3 = s2.count(str(x))
    print('{}의 갯수: {}개'.format(x, s3))

2017/11/17 18:24

장동영

python 2.7 초보 loop 버전 입니다.

sample = range(1, 1001)
numbs = []

for i in range(len(sample)):
    for j in str(sample[i]):
        numbs.append(j)

for k in range(10):
    cnt = numbs.count(str(k))
    print ('Number of %ds: %d' %(k, cnt))


2017/11/21 12:07

vkospi

list1 = []
for i in range(1,1001):
    str1 = str(i)
    list1 += list(str1)
#print(list1)
for x in range(0,10):
    print('{}의 갯수: {}'.format(x, list1.count(str(x))))

2017/11/22 13:21

장동영

python

countBox = [0 for i in range(10)]

for i in range(1, 1001):
    for j in range(10):
        num = str(i)
        countBox[j] += num.count('%d'%j)

print(countBox)

2017/11/23 16:02

이택성

nct = [0,0,0,0,0,0,0,0,0,0]

for x in range(1, 1001):
    a = list(map(int, list(str(x))))
    for c in a:
        nct[c]+=1

print (nct)

2017/11/23 16:55

Anny_hpk

from collections import Counter
data = []
for i in range(1, 1001) :
    s = str(i)
    # s = list(s)
    data.extend(s)
A = Counter(data)
print(A)

2017/11/30 18:36

# -*- coding: utf-8 -*-
a = str(range(1,1001))
for i in range(10):
    print "{}:{}개".format(i, a.count(str(i))),

2017/12/01 18:31

탐나

Swift

0부터 9까지 출력하는 for문이 작동이 안되서 인터넷 다른 예제에서 freq 함수를 가져왔습니다.

var chaList:[Character] = []
var numChar: String

extension Sequence where Self.Iterator.Element: Hashable {
    private typealias Element = Self.Iterator.Element

    func freq() -> [Element: Int] {
        return reduce([:]) { (accu: [Element: Int], element) in
            var accu = accu
            accu[element] = accu[element]?.advanced(by: 1) ?? 1
            return accu
        }
    }
}

for number in 1...999 {
    numChar = String(number)
    //print(numChar)
    for scalar in numChar.unicodeScalars {
        chaList += [Character(scalar)]
    }
}

//print(chaList)
//print(chaList.freq())

for (k, v) in chaList.freq() {
    print("\(k)의 갯수: \(v)개")
}

2017/12/04 23:09

장동영

C로 작성

#include <stdio.h>
int main(void){
    int i = 0;
    int j = 0;
    int max = 1000;
    int cnts[10] = {0,0,0,0,0,0,0,0,0,0};

    for(i=0;i<=max;i++){
        for(j=i;j>0;j=j/10){
            switch(j%10){
                case 0: cnts[0]++;break;
                case 1: cnts[1]++;break;
                case 2: cnts[2]++;break;
                case 3: cnts[3]++;break;
                case 4: cnts[4]++;break;
                case 5: cnts[5]++;break;
                case 6: cnts[6]++;break;
                case 7: cnts[7]++;break;
                case 8: cnts[8]++;break;
                case 9: cnts[9]++;break;
            }
        }
    }

    for(int idx=0; idx<10;idx++){
        printf("숫자 <%d>의 갯수는 <%d> \n", idx, cnts[idx]);
    }
    return 0;   
}

2017/12/05 12:51

Sooho Kim

 public static void main(String[] args) {
        int[] cnt=new int[10];

        for(int i=1;i<=1000;i++){
            Integer temp=i;
            String str[]=temp.toString().split("");
            for(int j=0;j<str.length;j++){
                cnt[Integer.parseInt(str[j])]++;
            }   
            }

        for(int i=0;i<cnt.length;i++){
            System.out.println(i+":"+cnt[i]);

        }

    }


2017/12/05 13:07

떼디

Common Lisp

(let ((s (make-string-output-stream)))
  (loop for n from 1 to 1000
        do (prin1 n s))
  (let ((f (get-output-stream-string s)))
    (map 'list (lambda (x) (count x f)) "0123456789")))

파이썬 풀이보고 따라해 봤습니다.

(let ((num-count-array (make-array 10)))
  (loop for n from 1 to 1000
        do (loop for c across (prin1-to-string n)
                 do (incf (aref num-count-array (digit-char-p c)))))
  num-count-array)
>#(192 301 300 300 300 300 300 300 300 300)

2017/12/07 12:56

리스프

import re

kk = []
for x in range(1,1001):
    kk.append(x)

kkk = ",".join(str(x) for x in kk)
for y in range(10):
    p = re.compile("{0}".format(y))
    q = p.findall(kkk)
    print("{0}:{1}개".format(y, len(q)))

2017/12/08 09:06

홍철현

Python 3

count = [0]*10

for i in range(1,1001): for j in str(i): count[int(j)] = count[int(j)] + 1

print(count)

2017/12/10 17:18

Taewon Song

arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for x in range(1, 1000 + 1):
    for idx in range(len(str(x))):
        arr[int(str(x)[idx])] += 1
print(arr)

2017/12/12 19:16

이형영

for i in range(10):
    nums=0
    for j in range(1, 1001):
        nums+=str(j).count(str(i))
    else:
        print('{}: {}개'.format(i, nums))

2017/12/13 03:11

빗나감

파이썬 3.6

def numbercount(a,b):
    numlist = []
    count = 0
    for i in range(a,b+1):
          for h in range(len(str(i))):
              numlist.append(str(i)[h])
    for g in range(10):
        for j in numlist:
            if int(g) == int(j):
                count += 1
        print(" ",g," : ",count,"개","\n")
        count = 0
    del numlist

start = int(input(" ▶ 범위 시작 숫자를 입력하세요(1~1000): "))
end = int(input(" ▶ 범위 끝의 숫자를 입력하세요(1~1000): "))
print("\n",">>> count 범위 : %d ~ %d" % (start, end),"\n")
numbercount(start, end)
  • 결과값
 ▶ 범위 시작 숫자를 입력하세요(1~1000): 10
 ▶ 범위 끝의 숫자를 입력하세요(1~1000): 15

 >>> count 범위 : 10 ~ 15 

  0  :  1 개 

  1  :  7 개 

  2  :  1 개 

  3  :  1 개 

  4  :  1 개 

  5  :  1 개 

  6  :  0 개 

  7  :  0 개 

  8  :  0 개 

  9  :  0 개 

2017/12/27 13:25

justbegin

s = ""
for i in range(1000):
    s += str(i+1)

for i in range(10):
    print("{} : ".format(str(i)),s.count("{}".format(i)),"개")

2017/12/28 17:23

이준우

lis = ''
for i in range(1,1001):
    lis = lis + str(i)

for i in range(10):
    j = lis.count('%d'%i)
    print('%d의 갯수는: %d' %(i,j))

2017/12/29 21:47

김호현

파이썬 입니다.

thou=[]
for i in range(1001):
    for j in range(len(str(i))):
        thou.append(str(i)[j])

for n in range(10):
    print('%d은 %d개'%(n,thou.count(str(n))))

2018/01/02 17:37

Ilhoon Kang

자바에요... 허허....


    final static int MIN = 1;
    final static int MAX = 1001;
    int num0 = 0;
    int num1 = 0;
    int num2 = 0;
    int num3 = 0;
    int num4 = 0;
    int num5 = 0;
    int num6 = 0;
    int num7 = 0;
    int num8 = 0;
    int num9 = 0;

    public static void main(String[] args)
    {
        main m = new main();

        StringBuilder sb = new StringBuilder();
        for(int i = MIN; i < MAX; i++)
        {
            sb.append(i);
        }

        for(int j = 0; j< sb.length(); j++)
            m.countingNum((int)sb.charAt(j) - 48);

        System.out.println("0: "+m.num0);
        System.out.println("1: "+m.num1);
        System.out.println("2: "+m.num2);
        System.out.println("3: "+m.num3);
        System.out.println("4: "+m.num4);
        System.out.println("5: "+m.num5);
        System.out.println("6: "+m.num6);
        System.out.println("7: "+m.num7);
        System.out.println("8: "+m.num8);
        System.out.println("9: "+m.num9);

    }

    public void countingNum(int num)
    {
        switch(num)
        {
        case 0:
            num0++;
            break;
        case 1:
            num1++;
            break;
        case 2:
            num2++;
            break;
        case 3:
            num3++;
            break;
        case 4:
            num4++;
            break;
        case 5:
            num5++;
            break;
        case 6:
            num6++;
            break;
        case 7:
            num7++;
            break;
        case 8:
            num8++;
            break;
        case 9:
            num9++;
            break;
        }
    }

2018/01/05 11:29

강승규

listx = []

for x in range(1001):
    listx += str(x)

for y in range(10):
    print(str(y) + ' : ' + str(listx.count(str(y))) + '개')

2018/01/05 12:55

황예환

lst = []

for x in range(1, 1001):
    if x % 10 == x: # 한 자리수
        lst.append(x)
    elif x % 100 == x: # 두 자리수
        lst.append(x // 10) # 10의 자리
        lst.append(x % 10) # 1의 자리
    elif x % 1000 == x: # 세 자리수
        lst.append(x // 100) # 100의 자리
        lst.append((x % 100) // 10) # 10의 자리
        lst.append((x % 100) % 10) # 1의 자리
    elif x % 10000 == x : # 네 자리수
        lst.append(x // 1000) # 1000의 자리
        lst.append((x % 1000) // 100) # 100의 자리
        lst.append(((x % 1000) % 100) // 10) # 10의 자리
        lst.append(((x % 1000) % 100) % 10) # 1의 자리

for x in range(10):
    print("{} : {}개".format(x , (lst.count(x))))

결과 0 : 192개 1 : 301개 2 : 300개 3 : 300개 4 : 300개 5 : 300개 6 : 300개 7 : 300개 8 : 300개 9 : 300개

2018/01/17 00:36

요한

python 3.6
for i in range(0,10):
    print(str(i),str(list(range(1,1001))).count(str(i)),"개")

2018/01/25 15:54

김도현

a = int(input("시작하는 수: "))
b = int(input("마지막 수: "))
def countnum(n1, n2):
    x = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for i in range(n1,n2+1):
        l = list(str(i))
        for j in l:
            x[int(j)] += 1
    return x
print(countnum(a, b))

2018/02/04 11:01

김동하

num<- function(x){
  x<-as.character(x)
  x<-strsplit(x, split = '')
  x<-table(unlist(x))
  return(x)
}

2018/02/07 15:15

김명중

#include <iostream>

using namespace std;
//숫자의 일의자리,십의자리,백의자리,천의자리수가 어떻게 되는지 확인하는 알고리즘 
int getNumber(int cipher,int number) // i는 숫자,j는 1~1000 
{
    int cnt = 0;

    while(number!=0)
    {
        if((number%10) == cipher)   cnt++;  
        number/=10; 
    }

    return cnt;
}

// 숫자i (0~10) 이 숫자 j(1~1000) 사이에 몇개 있는지 확인하는 알고리즘  
int main()
{
    int num[10] = {0};

    for(int i =0;i<10;i++)
    {
        for(int j=1;j<=1000;j++)
        {
            num[i] += getNumber(i,j);
        }
    }

    for(int i=0;i<10;i++)
    {
        cout << i << "의 개수:"<<num[i] << endl;
    }

    return 0;
}



2018/02/07 22:51

이승헌

s=''
for x in range(1,1001):s+=str(x)
for i in range(10):print(str(i)+':%d'%s.count(str(i)), end=' ')

2018/02/08 09:39

추천은 다 읽음

#include <Stdio.h>

void CountNumber(int arr[][10],int num){
    int i;
    for(i=0; i<10; i++){
        if(arr[0][i]==num) arr[1][i]++;
    }
}
int main(){
    int arr[2][10]={0,1,2,3,4,5,6,7,8,9};
    int n1, n2;
    int i, num;
    scanf("%d %d",&n1,&n2);
    for(i=n1; i<=n2; i++){
        num=i;
        while(num!=0){
            CountNumber(arr, num%10);
            num/=10;
        }
    }
    for(i=0; i<10; i++)
        printf("%d: %d개\n",i,arr[1][i]);
}

2018/02/10 16:48

gudrhrehd123

D언어 추가해주세요...

/*
 * - http://codingdojang.com/scode/504
 * - https://github.com/zhanitest/codingdojang.git
 */
import std.stdio;
import std.conv;

void main(){
  int[wchar] result;
  for(int i=1; i<1001; i++){
    foreach(wchar c; to!string(i)){
      if(c !in result)
        { result[c] = 0; }
      result[c] += 1;
    }
  }
  writeln(result);
}

2018/02/11 15:48

Kimbell Jone

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

int main(){
    int arr[2][10]={0,1,2,3,4,5,6,7,8,9};
    int i, k;
    int n1, n2;
    int num;
    memset(arr[1],0,sizeof(int)*10);
    scanf("%d %d",&n1,&n2);
    for(k=n1; k<=n2; k++){
        num=k;
        while(num!=0){
            for(i=0; i<10; i++){
                if(num%10==arr[0][i]){
                    arr[1][i]++;
                    break;
                }
            }
            num/=10;
        }
    }
    for(i=0; i<10; i++){
        if(arr[1][i]!=0)
            printf("%d: %d개\n",i,arr[1][i]);
    }
}

2018/02/12 20:37

gudrhrehd123

def number_counting():
    a=[]
    n=input('from 1 to~:')
    for i in range(1,n+1):
        for x in (str(i)):
            a.append(x)
    for j in range(0,10):
        b=a.count('%d'%(j))
        print ('%d:'%(j)),b

2018/02/13 16:34

Da ne

num_list=[]
for k in range(10):
    num_list.append(str(k))

num_str=''
for g in range(1,1001):
    num_str+=str(g)

ans_list=[]

for b in num_list:
    temp_num=num_str.count(b)
    if temp_num!=0:
        print(b+":"+str(temp_num)+"개")



2018/02/16 21:30

D B

public class numberAdd2 {

    int beginNumber = 1;
    int endNumber = 1000;
    int[] intArray = {0,0,0,0,0,0,0,0,0,0};

    public void numberSplit() {
        for(int i = beginNumber; i <= endNumber; i++) {
            String str = i + "";
            for(int j = 0; j < str.length(); j++) {
                setArray(Integer.parseInt(str.charAt(j)+""));
            }
        }
    }

    public void setArray(int idx) {
        intArray[idx] += 1;
    }

    public void display() {
        for(int i = 0; i < intArray.length; i++) {
            System.out.println(i + "숫자의 합은 :" + intArray[i] + "입니다.");
        }
    }
}

0숫자의 합은 :192입니다. 1숫자의 합은 :301입니다. 2숫자의 합은 :300입니다. 3숫자의 합은 :300입니다. 4숫자의 합은 :300입니다. 5숫자의 합은 :300입니다. 6숫자의 합은 :300입니다. 7숫자의 합은 :300입니다. 8숫자의 합은 :300입니다. 9숫자의 합은 :300입니다.

2018/02/26 13:39

초초보

nums = dict()
for a in range(1,1001):
    for b in str(a):
        nums[b] = nums.get(b, 0) + 1

for c in sorted(nums):
    print(c,nums[c])

결과

0:192 1:301 2:300 3:300 4:300 5:300 6:300 7:300 8:300 9:300

2018/03/07 09:13

김진영

def numberscount(lastnumber):
    result = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0}
    for number in range(1, lastnumber + 1):
        for args in str(number):
            count = result[int(args)]
            del result[int(args)]
            result[int(args)] = count + 1
    return result
print(numberscount(1000))

Python 3입니다 초보에다 딕셔너리를 잘 안써서 딕셔너리의 value가 변경되는 줄 모르고 코드를 이렇게 짰네요...

2018/03/11 19:05

myyh2357

#include <stdio.h>

int GetEachNumbers(int start, int end, int number)
{
    int i;
    int n, t;
    int ret = 0;

    for (i = start; i <= end; i++)
    {
        t = i;
        while (1)
        {
            n = t % 10; // 1의 자리 구하기    
            if (number == n)
            {
                ret++;
            }

            if (t < 10)
            {
                break;
            }

            t /= 10;
        }
    }

    return ret;
}

int main()
{
    int i;
    int number;
    int start, end;

    printf("start : ");
    scanf_s("%d", &start);

    printf("end : ");
    scanf_s("%d", &end);

    for (i = 0; i < 10; i++)
    {
        number = GetEachNumbers(start, end, i);

        if (0 < number)
        {
            printf("%d:%d개, ", i, number);
        }
    }
    printf("\n");

    return 0;
}

2018/03/13 21:59

이승훈

from collections import defaultdict
def test(n = 0,m = 0):
    s = ""
    temp = defaultdict(int)
    for i in range(n,m+1):
        for k in str(i):
            temp[k] += 1
    for i in sorted(temp.keys()):
        s += "%s:%s개,"%(i,temp.get(i))
    print(s[:-1])

if __name__ == "__main__":
    test(1,1000)

2018/03/16 15:05

김태우

public class Count{
 public static void main(String[] args){
  int i,j,k;
  int [] a = new int[10];

  for(i=0;i<1000;i++){
   String ChaNge = Integer.toString(i+1);
   int n = ChaNge.length();
   int input = (i+1);

   for(j=0;j<n;j++){
   int b = input%10;
   a[b] += 1;
   input=(int)(input/10);
   }

  }

  System.out.print("1~1000에서 각 숫자의 개수는 ");

  for(k=0;k<9;k++){
  System.out.print(k + ":" + a[k] + "개,");
  }

  System.out.print("9:" + a[9] + "개 입니다.");
 }
}

2018/03/20 20:21

배혜민

Swift입니다. 숫자 1부터 1000까지 모두 합쳐서 한개의 문자열을 만들고, 각 숫자를 카운트 했습니다.

import Foundation

var allNumbers = ""
for i in 1...1000 {
    allNumbers += String(i)
}

for j in 0...9 {
    print("\(j)) - \(String(allNumbers.filter {$0 == Character(String(j)) }).count)")
}

결과는..

0) - 192
1) - 301
2) - 300
3) - 300
4) - 300
5) - 300
6) - 300
7) - 300
8) - 300
9) - 300

2018/03/20 23:15

졸린하마

값을 하나하나 다 비교할려해서 C언어는 Switch문이 있으니까 더 편리하다 생각했는데 생각해보니 그렇게 할 필요가 없네요....

x,n = int(input("수를 입력하세요.")),[]
for x in range(1,x+1):
       s = list(str(x))
       for x in s:
              n.append(int(x))
for x in range(0,10):
       print("%d : %d" % (x,n.count(x)))

2018/03/22 23:06

김영성

arr = [0,0,0,0,0,0,0,0,0,0]

for inp in range(1,1001):
    tmp = str(inp)
    for j in tmp:
        arr[int(j)] += 1

for i in range(10):
    print(i,":", arr[i],"개")

2018/03/26 16:56

bnewkk

def thou(a,b) :
    num0, num1, num2, num3, num4, num5, num6, num7, num8, num9 = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    for i in range(a,b+1):
        for j in str(i) :
            if int(j) == 0 : num0 += 1
            elif int(j) == 1 : num1 += 1
            elif int(j) == 2:  num2 += 1
            elif int(j) == 3:  num3 += 1
            elif int(j) == 4: num4 += 1
            elif int(j) == 5: num5 += 1
            elif int(j) == 6: num6 += 1
            elif int(j) == 7: num7 += 1
            elif int(j) == 8:  num8 += 1
            elif int(j) == 9: num9 += 1
    return "0 : {0}개, 1 : {1}개, 2 : {2}개, 3 : {3}개, 4 : {4}개, 5 : {5}개, 6 : {6}개, 7 : {7}개, 8 : {8}개, 9 : {9}개".format(num0,num1,num2,num3,num4,num5,num6,num7,num8,num9)

print(thou(1,1000))

2018/03/27 16:17

yijeong

str1 = str(list(range(1,1001)))
for x in range(10):
    x = str(x)
    print(x, ":",str1.count(x))

2018/03/28 14:54

재즐보프

python 입니다.

text = ''
for n in range(1001): text = text + str(n)
for c in range(10): print(str(c), text.count(str(c)))

2018/03/30 15:35

무명소졸

파이썬

result = []
for i in range(1, 1000):
    result += str(i)

for i in range(0, 10):
    print("{}의 개수: {}".format(i, result.count(str(i))))

2018/04/04 21:34

이진우

dfsfafsfadfasdfasdfasdfasdfas

2018/04/06 13:10

김성표

a=str(list(range(1,1001)))
for i in range(0,10):
    print(str(i)+' : '+str(a.count(str(i))))

2018/04/06 13:18

thuruk

#include<iostream>
using namespace std;

int main()
{
    int remain, remain_100;
    int devide;
    int array[10] = { 0,1,2,3,4,5,6,7,8,9 };
    int array_count[10] = { 0,0,0,0,0,0,0,0,0,0 };

    int num = 1;
    int nano;

    for(int i=0;i<=1000;i++)
    {
        if (num > 99)           // 100부터는 100으로 나누고 몫값을 추가하여 count한다
        {
            remain_100 = num / 100;
            nano = num % 100;   // 100으로 나눈 나머지값을 저장한다
            remain = nano / 10; // 나머지값으로 10으로 나누고 몫값과 나머지 값을 count한다
            devide = nano % 10;
        }
        else if (num < 10)      //10 보다 작으면 10으로 나눈 나머지 값만으로 계산
            devide = num % 10;
        else
        {
            remain = num / 10;  
            devide = num % 10;
        }
        for (int j = 0; j < 10; j++)
        {
            if (remain == array[j])
                array_count[j]++;
            if (devide == array[j])
                array_count[j]++;
            if (remain_100 == array[j])
                array_count[j]++;
        }
        num++;
    }

    for (int i = 0; i < 10; i++)
    {
        cout << array[i] << "의 개수는>>" << array_count[i] << "개" << endl;
    }

}

2018/04/10 18:31

Jun ki Kim

옮기며 배우는 중입니다

        // 1~1000 각 숫자의 개수
        public void Test4()
        {
            var CntResult = new int[10];
            for (int i = 1; i <= 1000; i++)
            {
                //#1
                int iTmp = i;
                while (iTmp != 0)
                {
                    CntResult[iTmp % 10]++;
                    iTmp /= 10;
                }

                //#2
                //CntResult[i % 10]++;
                //if (i >= 10) CntResult[(i / 10) % 10]++;
                //if (i >= 100) CntResult[(i / 100) % 10]++;
                //if (i == 1000) CntResult[1]++;
            }
            for (int i = 0; i < 10; i++) Console.WriteLine($"{i} : {CntResult[i]}");
        }

2018/04/26 16:39

비트에이스

범위를 정하여 값 구하기

public class Number_Count {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int first_num;
        int second_num;
        int[] count_num = new int[10];
        String change;

        System.out.println("1 - 1000 까지의 수를 입력해주세요.");
        System.out.print("앞에 수를 입력하세요 > ");
        first_num = s.nextInt();
        char[] count = new char[first_num];
        System.out.print("뒤에 수를 입력하세요 > ");
        second_num = s.nextInt();

        System.out.println("범위 : " + first_num + "~" + second_num);

        for (int i = first_num; i <= second_num; i++) {
            change = String.valueOf(i);
            count = change.toCharArray();

            for (int k = 0; k < count.length; k++) {
                switch (count[k]) {
                case '0':
                    count_num[0]++;
                    break;
                case '1':
                    count_num[1]++;
                    break;
                case '2':
                    count_num[2]++;
                    break;
                case '3':
                    count_num[3]++;
                    break;
                case '4':
                    count_num[4]++;
                    break;
                case '5':
                    count_num[5]++;
                    break;
                case '6':
                    count_num[6]++;
                    break;
                case '7':
                    count_num[7]++;
                    break;
                case '8':
                    count_num[8]++;
                    break;
                case '9':
                    count_num[9]++;
                    break;
                default:
                    break;
                }
            }
        }
        for(int i = 0; i<10; i++){
            if(count_num[i]!=0){
                System.out.println(i+"의 수 :"+count_num[i]);
            }
        }
    }
}

2018/04/29 15:36

김현준

숫자들을 1,0, 1, 1, 1,2 .. 배열로 만들고 그룹으로 묶고, 각각을 카운트 했습니다. 워드카운트 참고해서 짯습니다.

(10 to 15).map(_.toString).flatten.groupBy(v => v).mapValues(_.size).foreach(println)

2018/05/01 12:38

한강희

// 자바
public static void main(String[] args) throws Exception {


        int[] nums = new int[10];

        for (int i=1; i<=1000; i++) {
            nums[i%10]++;
            if(i>=10)
                nums[(i/10)%10]++;
            if(i>=100)
                nums[(i/100)%10]++;
            if(i==1000)
                nums[1]++;
        }

        for (int i=0; i<10; i++) {
            System.out.println(i + "의 개수는 " + nums[i]);
        }
    }

2018/05/06 23:28

정몽준

// java version

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class MainClass {

    private static final int maximumPlace = 4;
    private Map<Integer, Integer> result = new HashMap<>();

    public static void main(String[] args) {
        // Test code - s
        Map<Integer, Integer> res = new MainClass().countDigit(10, 15);
        int arr[][] = {{0, 1}, {1, 7}, {2, 1}, {3, 1}, {4, 1}, {5, 1}};
        Map<Integer, Integer> testResult =
                List.of(arr).stream().collect(Collectors.toMap(a -> a[0], a -> a[1]));
        MainClass.testEquals(res, testResult);

        Map<Integer, Integer> res2 = new MainClass().countDigit(93, 105);
        int arr2[][] = {
            {0, 7}, {1, 7}, {2, 1}, {3, 2}, {4, 2}, {5, 2}, {6, 1}, {7, 1}, {8, 1}, {9, 8}
        };
        testResult = List.of(arr2).stream().collect(Collectors.toMap(a -> a[0], a -> a[1]));
        MainClass.testEquals(res2, testResult);

        Map<Integer, Integer> res3 = new MainClass().countDigit(115, 129);
        int arr3[][] = {
            {0, 1}, {1, 21}, {2, 11}, {3, 1}, {4, 1}, {5, 2}, {6, 2}, {7, 2}, {8, 2}, {9, 2}
        };
        testResult = List.of(arr3).stream().collect(Collectors.toMap(a -> a[0], a -> a[1]));
        MainClass.testEquals(res3, testResult);

        Map<Integer, Integer> res4 = new MainClass().countDigit(1, 100);
        int arr4[][] = {
            {0, 11}, {1, 21}, {2, 20}, {3, 20}, {4, 20}, {5, 20}, {6, 20}, {7, 20}, {8, 20}, {9, 20}
        };
        testResult = List.of(arr4).stream().collect(Collectors.toMap(a -> a[0], a -> a[1]));
        MainClass.testEquals(res4, testResult);
        // Test code - e

        Map<Integer, Integer> oneToThousand = new MainClass().countDigit(1, 1000);
        System.out.println("\n\n1 ~ 1000: result : " + oneToThousand.toString());
    }

    private Map<Integer, Integer> countDigit(int start, int end) {
        IntStream.rangeClosed(start, end)
                .forEach(
                        num -> {
                            while (num > 0) {
                                int remainder = num % 10;
                                int val = 1;
                                if (result.containsKey(remainder)) {
                                    val += result.get(remainder);
                                }
                                result.put(remainder, val);
                                num /= 10;
                            }
                        });

        return result;
    }

    // Test code
    private static void testEquals(Map<Integer, Integer> res, Map<Integer, Integer> testResult) {
        System.out.println(res.toString());
        System.out.println(testResult.toString());
        System.out.println(res.equals(testResult) ? "pass" : "fail");
    }
}

2018/05/07 01:00

Wilde Oscar

python version

map={'0':0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0}
for x in range(1, 1000 + 1):
    for d in str(x):
        map[d] = map.get(d) + 1
for key in map:
    print(key, ":", map.get(key))

2018/05/07 01:38

Wilde Oscar

go version

package main

import (
    "fmt"
)

func main() {
    result := make(map[int]int, 10)
    for i := 1; i < 1001; i++ {
        str := fmt.Sprint(i)
        for _, v := range str {
            j := int(v - '0')
            result[j] = result[j] + 1
        }
    }

    for i, v := range result {
        println(i, ":", v)
    }
}

2018/05/07 02:20

Wilde Oscar

C++ version

#include <iostream>
#include <sstream>
#include <map>

using namespace std;


int main()
{
    map<int, int> m;
    stringstream ss;
    char c;

    for (int i = 1; i < 1001; i++)
    {
        ss << i;

        while (ss.get(c))
        {
            int v = c - '0';
            m[v] = m[v] + 1;
        }
        ss.clear();
    }

    for (unsigned int i = 0; i < m.size(); i++)
    {
        cout << i << ":" << m[i] << endl;
    }

    return 0;
}

2018/05/07 02:59

Wilde Oscar

C version

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

int main()
{
    const int max = 1000;
    int number, digit, quotient, index;
    int v[10] = { 0, };
    size_t count = 4;
    char *c = (char*)malloc(sizeof(char) * count);

    for (number = 1; number <= max; number++)
    {
        _itoa_s(number, c, count + 1, 10);

        quotient = number;
        index = 0;
        while (quotient > 0)
        {
            digit = c[index++] - '0';
            v[digit] = v[digit] + 1;
            quotient /= 10;
        }
    }

    for ((size_t)number = 0; number < 10; number++)
    {
        printf("%d : %d\n", number, v[number]);
    }

    scanf_s("%d", &number);

    return 0;
}

2018/05/07 03:41

Wilde Oscar

num_count = [0,0,0,0,0,0,0,0,0,0]

for i in range(1,1001):
    for j in str(i):
        num_count[int(j)] += 1

print(num_count)

2018/05/14 02:36

이충경

파이썬 3.6

numlist = []
list0 = []
list1 = []
list2 = []
list3 = []
list4 = []
list5 = []
list6 = []
list7 = []
list8 = []
list9 = []
for i in range(1,1001):
    s = str(i)
    s = list(s)

    numlist.append(s)

for num in numlist:

    for k in num:
        if k == '0':
            list0.append(k)
        elif k == '1':
            list1.append(k)
        elif k == '2':
            list2.append(k)
        elif k == '3':
            list3.append(k)
        elif k == '4':
            list4.append(k)
        elif k == '5':
            list5.append(k)
        elif k == '6':
            list6.append(k)
        elif k == '7':
            list7.append(k)
        elif k == '8':
            list8.append(k)
        elif k == '9':
            list9.append(k)
answer = list([len(list0), len(list1), len(list2), len(list3), len(list4), len(list5), len(list6), len(list7), len(list8), len(list9)])
print(answer)

2018/05/23 13:54

Gerrad kim

list1 = str(list(range(1,1001)))
for i in "0123456789": print("{}: {}개".format(i, list1.count(i)))

# Output:
#0: 192개
#1: 301개
#2: 300개
#3: 300개
#4: 300개
#5: 300개
#6: 300개
#7: 300개
#8: 300개
#9: 300개

2018/05/27 16:34

재즐보프


public class Pratice1 {
    public static void main(String[] args) {
        int count[] = new int[10];
        for (int i = 1; i < 1001; i++)
            for (int j = 0; j < (i + "").length(); j++)
                count[Integer.valueOf((i + "").substring(j, j + 1))]++;
        for (int i = 0; i < count.length; i++)
            System.out.println(count[i]);
    }
}

2018/05/28 20:21

김지훈

data=[]

def main():
    for i in range(1,1001):
        for j in str(i):
            data.append(str(j))
    for k in range(10):
        print("{}:{}".format(k,data.count(str(k))))

if __name__=="__main__":
    main()

2018/05/30 17:15

조성은

Python

ans = [0]*10
a = 10
b = 15
for i in range(a, b+1):
    for c in str(i):
        ans[int(c)] += 1
for i, a in enumerate(ans):
    if a != 0:
        print("{}: {}".format(i, a), end=", ")

2018/05/31 14:01

Taesoo Kim

total_str = ""

for i in range(1,1001):
    total_str += str(i)

for i in range(10):
    print("{0}: {1}개".format(i, total_str.count(str(i))))

2018/06/05 23:05

meteor

count = {x: 0 for x in range(0, 10)}    # 딕셔너리 자료형 초기화

for num in range(1, 1001):
    for letter in str(num):
        count[int(letter)] += 1

for index in range(0, 10):
    print("{} : {}개".format(index, count[index]))

2018/06/17 01:14

Hand

for i in range(0,10):
    a= str(list(range(1,1001))).count(str(i))
    print("%s:%s개"%(i,a))

결과값: 0:192개 1:301개 2:300개 3:300개 4:300개 5:300개 6:300개 7:300개 8:300개 ```

2018/06/19 11:30

프로젝트1교통약자석

파이썬 입니다.

mydic={0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
for n in range(10):
    mydic[n]=str(list(range(1,1001))).count(str(n))
print(mydic)

2018/06/22 21:32

박종범

#include <stdio.h>

int main()
{
    int nList[6] = { 10,11,12,13,14,15 };
    int i;
    int zero = 0, one = 0, two = 0, three = 0, four = 0, five = 0;

    for (i = 0; i < 6; i++)
    {
        if (nList[i] / 10 == 1)
            one++;

        if (nList[i] % 10 == 0)
            zero++;
        else if (nList[i] % 10 == 1)
            one++;
        else if (nList[i] % 10 == 2)
            two++;
        else if (nList[i] % 10 == 3)
            three++;
        else if (nList[i] % 10 == 4)
            four++;
        else if (nList[i] % 10 == 5)
            five++;
    }

    printf(" zero: %d\n one: %d\n two: %d\n three: %d\n four: %d\n five: %d\n", zero, one, two, three, four, five);

    return 0;
}

최대한 간결하게 만들어봤습니다. C입니다

2018/06/23 16:37

임창우

n = range(1,1001)
count = {i:0 for i in range(10)}
for i in n:
    for j in str(i):
        count[int(j)] += 1

print(count)

# 결과
# {0: 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300}

2018/06/24 08:37

Creator

all=[]
for n in range(1,1001):
    n_list=[int(i) for i in str(n)]
    all += n_list

for i in range(10):
    count=all.count(i)
    print("%s:%s개" %(i,count))

<결과값> 0:192개 1:301개 2:300개 3:300개 4:300개 5:300개 6:300개 7:300개 8:300개 9:300개

2018/07/01 13:38

김규영

파이썬. Python

first_num = 1
last_num = 1000
count = [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]]

for i in range(first_num, last_num + 1):
    for j in count:
        for num in str(i):
            if str(j[0]) == num:
                j[1] += 1

for result in range(len(count)):
    print("%d: %d개" % (result, count[result][1]))

2018/07/08 02:57

eun

python 3.6.5

full_li=[]
for i in range(0,10):
    h=[]
    for j in range(1,1001):
        h.append(j)
    full_li.append(i)
    full_li.append(str(h).count(str(i)))

print(full_li)

음,,디넉셔리를이용하고싶지만 익숙하지않아서,,,연습해올게요ㅠㅠ

결과 : [ 0, 192 ,1, 301, 2, 300, 3, 300, 4,300 5,300, 6,300, 7,300, 8,300 , 9, 300 ]

2018/07/09 13:19

leak

num = int(input())

count = [0] * 10

for i in range(1,num+1):
    for j in str(i):
        count[int(j)] += 1

print(count)

2018/07/14 20:07

구름과비

zero = 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
seven = 0
eight = 0
nine = 0

for i in range(1,1001):
    number = str(i)

    if "0" in number:
        zero += 1
    if "1" in number:
        one += 1
    if "2" in number:
        two += 1
    if "3" in number:
        three += 1
    if "4" in number:
        four += 1
    if "5" in number:
        five += 1
    if "6" in number:
        six += 1
    if "7" in number:
        seven += 1
    if "8" in number:
        eight += 1
    if "9" in number:
        nine += 1

print("0 : %d개, 1 : %d개, 2 : %d개, 3 : %d개, 4 : %d개, 5 : %d개" % (zero,one, two, three, four, five))

2018/07/24 11:06

민수연

result = {}
for i in range(1,1001):
    for ch in str(i):
        if(ch in result):
            result[ch] += 1
        else:
            result[ch] = 1

print(result)

2018/07/29 22:08

박용주

c언어
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int i,j;
    int arr[10] = {0, }; //0~9를 가지기위하여 사용한 배열

    for(i=1; i<=1000; i++)
    {
        j = i;

        while(j>0)
        {

            arr[j%10]++; //0~9 값의 나머지의 범위를 저장 
            j = j/10;

        }
    }

    for(i=0; i<10; i++)
    {
        printf("%d은  %d  ", i,arr[i]);
    }
}

2018/08/03 08:05

이우경

a = []
for i in range(1, 1001):
    a.append(str(i))

b="".join(a)

for i in range(0, 10):
    print(i,  b.count(str(i)))

2018/08/05 08:04

이우경

#1~1000에서 각 숫자의 개수 구하기

data= {0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0} 

for i in range(10,16):
    text =str(i)
    for i in text:
        data[int(i)]+=1
print(data)

#{0: 1, 1: 7, 2: 1, 3: 1, 4: 1, 5: 1, 6: 0, 7: 0, 8: 0, 9: 0}

2018/08/11 15:40

S.H

def cn(x,y):
    dic = {}
    for i in range(x,y+1):
        for j in str(i):
            if j in dic:    
                dic[j] += 1
            else:
                dic[j] =1
    for i in sorted(dic.items()):
        print('{}:{}개'.format(i[0],i[1]))

2018/08/15 15:24

김동률

for x in range(10) : print(x, ':', str(list(range(1,1001))).count(str(x)))

2018/08/22 02:55

김미성

lst = []

for n in range(1, 1001):
    for c in str(n):
        lst.append(int(c))

# 출력
for n in range(10):
    str_n = str(n)
    print(str_n+': %d개' % lst.count(n))

2018/08/22 18:51

이충각

num_list = [];
for num = 1 : 1000
    split_num = num2str(num) - '0';
    num_list = [num_list, split_num];
end
for i = 0 : 9
    numnum = length(find(num_list == i));
    fprintf('%d: %d개\n', i, numnum);
end

2018/08/25 01:06

njlee

cnt={}

for i in range(10):
    cnt[i]=0

for i in range(1,1001):
    for x in range(10):
        cnt[x]+=str(i).count(str(x))

print(cnt)

2018/08/27 21:47

전형진

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int sumList[10];
    int i;
    for (i=0; i<10; i++) {
        sumList[i] = 0;
        //std::cout << sumList[i];
    }

    int start = 0;
    int end = 1000;
    int digit;
    for (i=start; i<=end; i++) {
        int currentNumber = i;
        //std::cout << '\n' << i << " : ";
        // find digits
        while (10 <= currentNumber) {
            digit = currentNumber % 10;
            //cout << digit << ", ";
            sumList[digit]++;
            currentNumber = currentNumber/10;   // int divide on purpose
        }
        sumList[currentNumber]++;
    }

    cout << '\n';
    for (i=0; i<10; i++) {
        std::cout << i << ":" << sumList[i] << ", ";
    }
}

답은 0:193, 1:301, 2:300, 3:300, 4:300, 5:300, 6:300, 7:300, 8:300, 9:300,

2018/08/27 23:16

phg98

list_data=[]
for i in range(1,1001):
    data=','.join(str(i))
    data=data.split(',')
    for o in data:
        list_data.append(int(o))

for i in range(0,10):
    number=list_data.count(i)
    print('%s의 개수는 %s개 입니다.' % (i,number)) 

초보에염 히히

2018/09/09 23:35

김김김

def counter(start, end) :

    num_str = '1234567890'
    start_end_dict = {}

    for i in num_str :

        num = 0

        for j in range(start, end+1) :

             num += str(j).count(i)

        start_end_dict[i] = num

    return start_end_dict

2018/09/14 19:44

박강민

파이썬 3.7입니다.

from collections import Counter
a, b, *_ = [int(x) for x in input().split(' ')]
c = Counter(''.join(str(x) for x in range(a, b+1)))
for k, v in c.items():
  print(f'{k}: {v}')

2018/09/17 19:45

룰루랄라

result = {}
for i in range(1,1001):
    number = str(i)
    for num in number:
        if num in result:
            result[num] += 1
        else:
            result[num] = 1

print(result)

2018/09/30 15:01

윤종석

def count_num(n):
    str_num = str(n)
    s = set()

    for i in range(len(str_num)):
        if str_num[i] in s:
            pass
        else:
            s.add(str_num[i])
    print(len(s))

2018/10/01 21:56

SeonKyu Kim

s = int(input("시작 값:"))
e = int(input("마지막 값:"))

num_line = ""

for i in range(s, e+1):
    num_line += str(i)

n = 0
while n < 10:
    if num_line.count(str(n)) > 0:
        p = int(num_line.count(str(n)))
        print("%d:%d개" %(n, p), end=', ')
        n += 1
    else:
        n += 1

2018/10/05 22:35

농창

import java.util.*;


public class NumCount {

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

        int num[] = new int[10];

        Scanner sc = new Scanner(System.in);

        System.out.print("처음 값 : ");
        int count_start = sc.nextInt();

        System.out.print("마지막 값 : ");
        int count_end = sc.nextInt();

        for (int i=count_start ; i<=count_end ; i++)
        {
            num[i%10]++;
            if(i>9)
                num[(i/10)%10]++;
            if(i>99)
                num[(i/100)%10]++;
            if(i>999)
                num[(i/1000)%10]++;
        }

        for(int i=0 ; i<num.length ; i++)
            System.out.println(i + "의 개수 : " + num[i]);

    }

}

2018/10/20 14:48

용희

[str(list(range(1,1001))).count(str(x)) for x in range(10)]

리스트를 문자열로 바꿔 0의 개수 ~ 9의 개수를 찾아 리스트화했습니다.. 파이썬 버전은 3이상입니다. [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

2018/10/26 19:24

# TDAT

thousand = list(range(1,1001))

zero = 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
seven = 0
eight = 0
nine = 0

for i in thousand:
    zero += str(i).count(str(0))
    one += str(i).count(str(1))
    two += str(i).count(str(2))
    three += str(i).count(str(3))
    four += str(i).count(str(4))
    five += str(i).count(str(5))
    six += str(i).count(str(6))
    seven += str(i).count(str(7))
    eight += str(i).count(str(8))
    nine += str(i).count(str(9))

print(zero,one,two,three,four,five,six,seven,eight,nine)

2018/11/05 22:27

그사람 남한 볼 수 있어요

public class KimSanghyeop
{
    public static void main(String[] args)
    {
        int f1;
        int temp;
        int[] arr_cnt= new int[10];

        for(f1=1;f1<=1000;f1++)
        {
            temp=f1;
            while(temp!=0)
            {
                arr_cnt[temp %10]+=1; 
                temp=temp/10;
            }
        }

        for(f1=0;f1<arr_cnt.length;f1++)
        {
            System.out.println(f1+" : "+arr_cnt[f1]);
        }
    }
}

2018/11/06 14:03

김상협

num_list=[0,0,0,0,0,0,0,0,0,0]
for x in range(1,1001):
    if 1<=x<10:
        num_list[x]+=1
    elif 10<=x<100:
        num_list[x//10]+=1
        num_list[x%10]+=1
    elif 100<=x<1000:
        num_list[x//100]+=1
        num_list[(x//10)%10]+=1
        num_list[(x%100)%10]+=1
    elif x==1000:
        num_list[1]+=1
        num_list[0]+=3
for x in range(0,10):
    print(x,':',num_list[x],'개')

2018/11/07 00:21

빅디펜스

upper = int(input("상한입력:"))
lower = int(input("하한입력:"))

target =range(upper,lower+1)
null=[]
for i in target:
    for j in range(0,len(str(i))):
        null.append(int(str(i)[j]))

for k in range(min(null),max(null)+1):
    print(k,":",null.count(k),"개")

2018/11/12 14:34

배득주

for i in range(0,10):
    cnt = 0
    for num in range(1,1001):
        cnt+=str(num).count(str(i))

    print('{}의 갯수는 {}개 입니다.'.format(i,cnt))

2018/11/28 19:26

현모구

box = {}

for i in range(1, 1001) :
    list_ = list(str(i))
    for j in list_:
        if j in box :
            box[j] += 1
        else:
            box[j] = 1

print(box)

2018/11/28 23:50

lucky1to10

Java 8

import java.time.Duration;
import java.time.LocalTime;
import java.time.Period;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class tut03 {
  public static void main(String[] args) throws InterruptedException, ExecutionException {
    System.out.println("hello world");

    // 시작~종료 Parameter
    int startNum = 1;
    int endNum = 1000;

    // 0~9 까지 Map 을 만든다.
    Map<Integer, Integer> map = IntStream.rangeClosed(0, 9).boxed()
        .collect(Collectors.toMap(Function.identity(), i -> i * 0));

    // 시작 시간 기록
    LocalTime currentDate = LocalTime.now();
    System.out.println("start time    : " + currentDate);

    // 숫가 Count
    for (int i = startNum; i <= endNum; i++) {
      (i + "").chars().forEach(k -> {
        int number = (k-'0');
        map.put(number, map.get(number)+1);
      });
    }

    // 종료시간 기록.
    LocalTime completeDate = LocalTime.now();
    System.out.println("complete time : " + completeDate);

    // 간격 계산
    Duration duration = Duration.between(currentDate, completeDate);
    System.out.println("duation : " + duration.getSeconds());

    // 결과 확인.
    map.forEach((k,v) -> {
      System.out.println("Number : " + k + ", Count : " + v);
    });
  }
}

2018/11/30 11:09

public class NumCount {

    public static void main(String[] args) {
        int[] n = new int[10];
        for(int i = 1; i <=1000; i++) {
            //숫자 자르기
            String s = Integer.toString(i);
            for(int j = 0; j <s.length(); j++) {
                //해당 숫자 개수 증가
                n[s.charAt(j) - '0']++;
            }
        }
        for(int k=0; k < n.length; k++) {
            System.out.printf(k + " : " + n[k] + " ");
        }
    }

}

2018/12/19 22:35

이동훈

digitDic = {}
for digit in range(10, 16):
    for s in str(digit):
        digitDic[s] = digitDic.get(s, 0) + 1
print(digitDic)

2019/01/02 17:26

선선모

# 105_number_of_each_number_between_1_and_1000.py

def count(num):
    res = {}
    for k in range(0,10):
        res[k] = 0
    for i in str(num):
        for k in range(0, 10):
            if int(i) == k:
                res[k] += 1
    return res

total_res = {}
for k in range(0, 10):
    total_res[k] = 0

for i in range(1,1001):
    num_res = count(i)
    for k in range(0, 10):
        total_res[k] += num_res[k]

print(total_res)

2019/01/03 11:37

판다네밥상

def mat_counter(input_int):
    temp = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    for num in range(1, input_int + 1):
        for i in str(num):
            temp[int(i)] += 1

    for i in range(len(temp)):
        print("{0}:{1}개".format(i, temp[i]), end=" ")

def main():
    user_input = int(input("Input integer : "))
    mat_counter(user_input)

if __name__ == '__main__':
    main()

2019/01/04 14:06

김범식

number = dict()

for i in range(10):
    number[str(i)] = 0

for i in range(1,1001):
    list_i = list(str(i))
    for j in range(len(list_i)):
        number[list_i[j]] += 1

print(number)

2019/01/04 23:27

Woohyuck Choi

namespace codingdojang__
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

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

                while (temp != 0)
                {
                    array[temp % 10] += 1;

                    temp /= 10;
                }
            }

            foreach (var i in array)
            {
                Console.WriteLine(i);
            }
        }
    }
}

2019/01/06 12:02

bat

for i in range(10):
    print("%d : %d" % (i, "".join([str(x) for x in range(1,1001)]).count(str(i))))

Python 3.7.2

2019/01/17 04:16

전주원

temp = [0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    istr = str(i)
    for t in istr:
        temp[int(t)] += 1

for i in range(10):
    print(i,':',temp[i],'개')

2019/01/17 16:48

D.H.


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

        int zero=0;
        int one =0;
        int two=0;
        int three=0;
        int four=0;
        int five=0;

        for(int i=10; i<=15;i++) {
            String str = "" + i;
            for(int j=0; j<str.length();j++) {
                switch(str.charAt(j)) {
                case '0': zero++;
                break;
                case '1': one++;
                break;
                case '2': two++;
                break;
                case '3': three++;
                break;
                case '4': four++;
                break;
                case '5': five++;
                }
            }
        }
        System.out.println("zero:" + zero + " one:" + one + " two:" + two + " three:" + three + " four:" + four + " five:" + five);
    }
}

2019/01/21 12:50

고요정

자바로 풀었습니다~ 0~6 으로만 구성되어있기 때문에 길이가 6인 배열을 사용했습니다.


class TenToFif2 {
    public static void main(String[] args) {
        //0부터 6까지만 존재함
        int[] intArr = new int[6];

        for(int i=10; i<=15; i++) {
            String str = "" + i;
            for(int j=0; j<2;j++) {
                ++intArr[((int)(str.charAt(j))-48)];
            }
        }

        for(int i= 0; i<intArr.length;i++) {
            System.out.println(i + ": " + intArr[i]);
        }
    }
}

2019/01/21 13:02

고요정

# -*- coding: utf-8 -*-
'''
Title           : 1 ~ 1,000 사이에서 각각의 숫자값 카운팅 구하기
Check Point     : 0 ~ 9 항목 및 카운팅 값을 이중 리스트로 표현,
'''

# import

# define
LIMIT_  = 1000
item    = [
        [0, 0],
        [1, 0],
        [2, 0],
        [3, 0],
        [4, 0],
        [5, 0],
        [6, 0],
        [7, 0],
        [8, 0],
        [9, 0],
]

# function

# exception

# body
for num in range(LIMIT_):                                               # 0 ~ 1,000
        buf = str(num)                                                  # e,g, '123' -> ['1', '2', '3']
        for head in range(len(item)):                                   # 0 ~ 9
                for i in range(len(buf)):                               # e.g., '123' -> 0 ~ 2
                        if (buf[i] == str(item[head][0])):              # e.g., if ('2' == str(2))
                                item[head][1] = item[head][1] + 1       # e.g., ['2', '0'] -> ['2', '1']

for num in range(len(item)):                                            # 결과값 출력
        print ("Counted value of %s th is %s." % (item[num][0], item[num][1]))

2019/01/21 14:11

몽실이

num_list=[]

for str_num in range(1,1001):
    num_list.append(str_num) 
    print(num_list)

for i in range(10):
    print(i,':',num_list.count(str(i)))

2019/01/23 21:54

jj kim

def number(a):
    result=0
    for x in range(1,1001):
        result+=str(x).count(str(a))

    return result

2019/01/23 22:48

Lapis

function count(){
  const memory = []
  for(let i=1; i<1001; i++){
    const splittedNum = String(i)
    for(let j =0; j<splittedNum.length; j++){
      memory.push(splittedNum[j])
    }
  }
  const result =[]
  for(let r=0; r<memory.length; r++){
    let count = 0
    for(let m =0; m<memory.length; m++){
      if(memory[m] === String(r)){
        count+=1
      }
    }
    result.push(count)
  }
  return `0: ${result[0]}개, 1: ${result[1]}개, 2: ${result[2]}개, 3:${result[3]}개, 4: ${result[4]}개, 5: ${result[5]}개, 6: ${result[6]}개, 7: ${result[7]}개, 9: ${result[9]}개`
}

count()

2019/01/24 11:09

돌도끼

R 로 작성하였습니다

tmp =  data = c()
for(i in 1:1000){
  i = strsplit(as.character(i), "")[[1]]
  tmp = append(tmp, i)
}

count = 0
for(j in 0:9){
  for(i in 1:length(tmp)){
    if(as.numeric(tmp[i]) == j){
      count = count + 1
    }
  }
  tmp.vec = append(tmp.vec, count)
  count = 0
}

2019/01/29 10:44

강창구

파이썬 입니다.

정답: [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

ls = [0,0,0,0,0,0,0,0,0,0]

for i in range(1,1001):
    for j in str(i):
        ls[int(j)] += 1

print(ls)

2019/01/29 23:48

손경배

result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(1,1001):
     for number in str(i):
         result[int(number)] += 1

for i in range(10):
    print('%d : %d개' %(i, result[i]))

2019/01/30 21:27

손태호

start = 1
end = 1000
digits = dict()

for i in range(10):
    digits[i] = 0

for x in range(start, end+1):
    for a in str(x):
        digits[int(a)] += 1

print(digits)

2019/01/31 15:56

ChungGeol You

각 자리를 문자열 리스트로 변환 후 .count 를 통해 Dictionary형태로 출력하는 코드입니다.

def func(a, b):

    slice_list = []
    count_dict = {}

    for i in range(a, b + 1):
        for j in range(0, len(f"{i}")):
            slice_list.append("".join(f"{i}"[j]))

    for k in range(10):
        if slice_list.count(f"{k}") != 0:
            count_dict[k] = slice_list.count(f"{k}")

    return count_dict


print(func(10, 15))
{0: 1, 1: 7, 2: 1, 3: 1, 4: 1, 5: 1}

print(func(1, 1000))
{0: 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300}

2019/01/31 21:31

x monciel

[Python] {숫자: 갯수} 형태의 Dictionary값으로 출력하는 코드

def func(a, b):
    slice_list = [j for i in range(a, b + 1) for j in str(i)]

    count_dict = {n:slice_list.count(f"{n}") for n in range(10) if slice_list.count(f"{n}") != 0}

    return count_dict
print(func(1, 1000))
{0: 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300}

2019/02/01 21:10

x monciel

include

using namespace std;

int CountNum();

int main(void){ int countnum[20]; int k = 0; int sumnum[10] = { 0, };

for (int i = 10; i <= 15; i++){
    countnum[k] = (i / 10);
    countnum[k + 1] = (i % 10);
    k = k + 2;
}

for (int t = 0; t < 12 ; t++){
    for (int j = 0; j < 10; j++){
        if (countnum[t] == j){
            sumnum[j] = sumnum[j] + 1;
        }
    }
}

for (int s = 0; s < 10; s++){
    cout << s << " 갯수 : " << sumnum[s] << endl;
}

return 0;

}```{.cpp}

include

using namespace std;

int CountNum();

int main(void){ int countnum[20]; int k = 0; int sumnum[10] = { 0, };

for (int i = 10; i <= 15; i++){
    countnum[k] = (i / 10);
    countnum[k + 1] = (i % 10);
    k = k + 2;
}

for (int t = 0; t < 12 ; t++){
    for (int j = 0; j < 10; j++){
        if (countnum[t] == j){
            sumnum[j] = sumnum[j] + 1;
        }
    }
}

for (int s = 0; s < 10; s++){
    cout << s << " 갯수 : " << sumnum[s] << endl;
}

return 0;

} ```

2019/02/03 11:54

박태준

using System;

class Test
{
    public static void Main(string[] args)
    {
        int i, k;
        int nam, mok;
        int start = 1; int end = 1000;
        int[] keyList = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int[] countList = new int[10];
        for(i = start; i < end + 1; i++)
        {
            mok = i;
            while(mok>0)
            {
                nam = mok % 10;
                for(k = 0; k < 10; k++)
                {
                    if(nam == keyList[k])
                    {
                        countList[k] = countList[k] + 1;
                    }
                }
                mok = mok / 10;
            }
        }
        Console.WriteLine();
        for (k=0; k < 10; k++)
        {
            if(countList[k]!=0)
            {
                Console.Write("{0:d}:{1:d}\t", k, countList[k]);
            }
        }
        Console.WriteLine();
    }
}

Visual Studio 2019 C# 기준으로 작성했습니다.

2019/02/05 16:54

조재현

public class Numbers {
    public static void main(String[] args){
        int[] count = new int[10];

        for(int i = 1; i <= 1000; i++){
            for(int j=i; j>0;j /= 10)
                count[j%10]++;
        }

        for(int i = 0; i<10;i++){
            System.out.println(i+ " : " + count[i]);
        }
    }
}

2019/02/07 22:57

김동수

perl v5.20.2 built for MSWin32-x64-multi-thread

수정1. 주석추가.

#참고 : http://effectiveperl.blogspot.com/2006/01/idiomatic-perl-counting-number-of.html

use strict; #착한 펄린이는 꼭 씁니다.
use warnings; #착한 펄린이는 꼭 씁니다.
my @number=(0,0,0,0,0,0,0,0,0,0);#0,1,2,3,4,5,6,7,8,9의 개수
for(my $num=0;$num<10;$num++)
{
    for(my $i=1;$i<1001;$i++)
    {
        foreach my $substring (split(//, "$i"))
        { #$i를 문자열로 만들고, 이를 split으로 각 문자마다 쪼개어 $substring에 전달.
            if($substring eq "$num")
            { #$num 을 문자열로 만들고 $substring과 같은지 문자열 비교.
                $number[$num]++;
            }
        }
    }
    print "$num의 개수 : $number[$num]\n";
}

아름답구나 split.

2019/02/09 04:33

Uranus

def solution(a,b):
    ans = dict()
    string =''
    for i in range(a,b+1):
        string += str(i)
    for i in range(0,10):
        ans[i] = string.count(str(i))
    return ans

answer : {0: 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300}

2019/02/09 17:33

dodoman

import collections
empty = ""
box = collections.Counter()
for i in range(1,1001):
    a = str(i)
    empty += a
box.update(empty)
print(box)

2019/02/12 14:05

김규묭

gesu = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(1, 1001) :
    toStr = str(i)
    for j in toStr :
        toInt = int(j)
        gesu[toInt] += 1
for k in range(10) :
    print("%d:%d개"%(k, gesu[k]), end=", ")

2019/02/12 14:29

좋은나쎔

import java.util.Arrays;

public class Problem2 {

    public static void main(String[] args) {
        int count[] = new int[10];
        for(int i=1;i<=1000;i++) {
            count[i%10]++;
            if(i>=10)
                count[i/10%10]++;
            if(i>=100)
                count[i/10/10%10]++;
            if(i>=1000)
                count[i/10/10/10%10]++;
        }
        System.out.println(Arrays.toString(count));
    }

}

2019/02/12 22:54

송인성

var obj = {};
var a = 1 , b = 1000;

for (var i = a; i <= b; i++) {
    var tmp = i;
    while (tmp > 0) {
        var num = tmp % 10
        if (obj[num]) {
            obj[num]++;
        } else {
            obj[num] = 1;
        }
        tmp = parseInt(tmp / 10);
    }
}
var temp = '';

Object.keys(obj).map(function (key, index) {
    temp += key + ":" + obj[key] + '개 ';
});

console.log(temp);

2019/02/12 23:43

이계민

let answer = {}
for(num = 1; num <= 1000; num++) {
    let str = String(num)
    for(let i = 0; i < str.length; ++i) {
        if(answer[Number(str.charAt(i))] == undefined) answer[Number(str.charAt(i))] = 1
        else answer[Number(str.charAt(i))]++
    }
}

2019/02/13 18:53

YEAHx4

def count(start,end):
    dict={}
    for i in range(start,end+1):
        for j in list(str(i)):
            if j not in dict: dict[j]=1 
            else: dict[j]+=1
    return dict

print(count(1,1000))

2019/02/14 19:03

얀차

def count_number():
    cnt=[0,0,0,0,0,0,0,0,0,0]
    for i in range(1,1001):
        for j in str(i):
            cnt[int(j)]+=1
    return cnt

2019/02/21 18:00

쨔이

count_list=[0,0,0,0,0,0,0,0,0,0]

for num in range(10,16):
    for index in str(num):
        count_list[int(index)]+=1

print(count_list)

2019/02/25 17:05

s = ""
for i in range(1001):
    s += str(i)

for i in range(10):
    print(s.count(str(i)))

2019/02/28 17:28

이세훈

R 코딩

num<-10:15
result<-as.data.frame(table(unlist(strsplit(as.character(num),''))))
names(result)<-c("number","count")
result

PYTHON 코딩(3버전)

strnum=''
for i in range(1,1001):
    strnum+=str(i)

for i in range(0,10):
    print("{}의 갯수 : ".format(i),strnum.count(str(i)))

2019/02/28 18:03

원대훈

count=[0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    for s in str(i):
        count[int(s)]+=1

print("From 1 to 1000,")
for i in range(10):
    print("{0} appears {1} times.".format(i,count[i]))

2019/02/28 20:19

ykleeac

accumul=str()
for i in range(1,1001):accumul+=str(i)
for j in range(10):print('%d:%d'%(j,accumul.count(str(j))))

2019/03/01 23:43

Hyeonu Cho

def number(x,y):
    dic={}
    for i in list(range(x,y + 1)):
        for j in str(i):              
            if j not in dic:
                dic[j] = 1
            else:
                dic[j] +=1
    dic = sorted(dic.items())
    for i in dic:
        print("{}:{}개".format(i[0], i[1]))

number(1,1000)

2019/03/09 20:42

김동률

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main()
{
    int from, to;
    int count[10] = { 0, };

    printf("구하려는 숫자 범위 입력 ex. 10 15 : ");
    scanf("%d %d", &from, &to);

    if (from < to && to <= 1000) {
        for (int i = from; i <= to; i++) {
            if (i < 10) {
                count[i]++;
            }
            else if (i >= 10 && i < 100) {
                count[i / 10]++;
                count[i % 10]++;
            }
            else if (i >= 100 && i < 1000) {
                count[i / 100]++;
                count[(i % 100) / 10]++;
                count[(i % 100) % 10]++;
            }
            else if (i == 1000) {
                count[0] += 3;
                count[1]++;
            }
        }

        for (int i = 0; i < 10; i++) {
            if(count[i] != 0)
                printf("%d: %d개 ", i, count[i]);
        }
        printf("\n");
    }
    else
        printf("범위에 맞게 입력하세요\n");
}

C로 풀어봤습니다

2019/03/17 11:37

황정인

result = dict()
for i in range(10):
    result[i]=0
for n in range(1,1000):
    for i in str(n):
        result[int(i)]+=1
print(result)

2019/03/19 22:16

한상준

파이썬 3.7.2버전 입니다.
k = str(list(range(1, 1001)))
for t in range(0,10):
    print(f'{t} are {k.count(str(t))}','/',end='')

2019/03/21 01:05

이우현


for i in range(0,10):
    print('1~1000에서 %d의 갯수는' %i, str(list(range(1,1001))).count(str(i)), '입니다')


2019/03/21 20:10

김성근

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

void main() {

    int cnt[10] = { 0, };
    for (int i = 1; i <= 1000; i++)
    {
        cnt[i % 10]++;
        if (i >= 10 && i < 100)
        {
            cnt[i / 10]++;
        }
        if (i >= 100 && i < 1000)
        {
            cnt[i / 100]++;
            cnt[i / 10 % 10]++;
        }
        if (i == 1000)
        {
            cnt[i / 1000]++;
            cnt[i / 100 % 10]++;
            cnt[i / 10 % 10]++;
        }
    }
    for (int i = 0; i < 10; i++)
    {
        cout << i << "의 개수 : " << cnt[i] << endl;
    }
}

2019/03/26 14:55

Albert

print([str([x for x in range(1,1001)]).count(str(y)) for y in range(0,10)])

2019/04/04 15:44

권의준

def find_same_number(start, end):
    numbers = range(start, end + 1)
    str_numbers = []
    for num in numbers:
        print(num)
        str_numbers += list(str(num))

    number_dict = {}
    for n in str_numbers:
        if n in number_dict:
            number_dict[n] += 1
        else:
            number_dict[n] = 1

    print(number_dict)

find_same_number(1, 1000)

2019/04/09 17:29

Nonamed

countlist = [0,0,0,0,0,0,0,0,0,0]

for num in range(1,1001):
    for i in str(num):
        k = int(i)
        countlist[k] += 1

for j in range(0,10):
    print(f"{j}:{countlist[j]}개", end = " ")

2019/04/18 00:27

Wonjin Park

a = {'0':0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0}

for i in range(1, 1001):               
    for j in str(i):                       
        a[j]+=1                         

for i in a:                                
    print("%s: %d개" %(i, a[i]))      

2019/04/18 18:44

cheer

Input = [x for x in range(1, 1001)]

for i in range(10):
    print('{0}: {1}'.format(i, str(Input).count(str(i))))

2019/04/18 20:45

Hwaseong Nam

python3 입니다

num = []
for i in range(1,1001):
    for j in str(i):
        num.append(j)

for j in range(10):
    n = num.count(str(j))
    print(f'{j}은 {n}개')

2019/04/21 15:42

sjm

count_num={j:0 for j in range(10)}

for n in range(1,1001):
    for i in str(n):  
        count_num[int(i)]+=1

print(count_num)

2019/04/30 22:31

암살자까마귀

선형시간으로 끝내는 솔루션은 old_func, 상수시간으로 끝내는 솔루션은 new_func

#include <iostream>
using namespace std;

void old_func(int cnt[10], int N)
{
    for(int i = 1 ; i <= N ; i++)
    {
        for(int j = 1; i/j > 0 ;j*=10)
        {
            cnt[i / j % 10]++;
        }
    }
}
void new_func (int cnt[10], int N)
{
    for(int i = 1 ; N/i > 0 ; i*=10)
    {
        if(0 == N / i %10)
        {
            cnt[0] += (N / (10 * i) -1) * i + 1 + N % i;
        }
        else
        {
            cnt[0] += (N / (10 * i)) * i;
        }

        for(int j = 1 ; j <= 9 ; j++)
        {

            if(N / i % 10 < j)
            {
                cnt[j] += (N / (10 * i)) * i;
            }
            else if(j == N / i %10)
            {
                cnt[j] += (N / (10 * i)) * i + 1 + N % i;
            }
            else
            {
                cnt[j] += (N / (10 * i) + 1) * i;
            }
        }
    }

}


int main(void)
{
    /*
    for(int i = 1; i< 10000; i++)
    {
        int cnt1[10]= {0,};
        int cnt2[10] = {0,};
        old_func(cnt1, i);
        new_func(cnt2, i);
        for(int j = 0 ; j <= 9 ;j++)
        {
            if(cnt1[j] != cnt2[j]){
                cout << "They are different!" <<endl;
            }
        }
    }*/

    int N;
    int cnt1[10] = {0,};
    int cnt2[10] = {0,};
    scanf("%d", &N);
    old_func(cnt1, N);
    new_func(cnt2, N);
    cout << "Time Complexity O(N) Solution" << endl;
    for(int i = 0; i <= 9 ; i++)
        cout << cnt1[i] << ' ';
    cout << '\n';
    cout << "Time Complexity O(1) Solution" << endl;
    for(int i = 0; i <= 9 ; i++)
        cout << cnt2[i] << ' ';
    cout << '\n';
    return 0;
}


2019/05/01 12:58

이기준

std::cout << "START TEST :: " <<std::endl;

int array_list[10] = {0,};
int input_a = 10, input_b = 15;

for(int i = input_a; i <=input_b; i++){
    int temp = i;
    while(temp > 0){
        array_list[temp%10]++;
        temp/=10;
    }

}

for(int j = 0; j< 10; j++){
   std::cout << "Count : "<< j << "::";
   std::cout << array_list[j] << std::endl;
}

2019/05/09 17:11

Jung Wookyeong

파이썬 3.7.2

while True:
    count = { i:0 for i in range(0, 10) }
    A1 = input("\n\n시작할 수를 정해주세요.\n> ")
    A2 = input("끝낼 수를 정해주세요. \n> ")
    limit = [int(A1), int(A2)]
    for x in range(limit[0], limit[1]+1):
        for y in str(x):
            count[int(y)] += 1
    for i in range(len(count)):
        print(str(i)+"이 "+str(count[i])+"개")

2019/05/14 17:23

CT_EK

from collections import Counter

a=range(1,1001)
b=[]

for i in a:
    b+=str(i)

print(Counter(b))

2019/05/15 15:03

코딩동댕유치원

python3.6

counting_num = {i: 0 for i in range(0,10)}
for j in range(1, 1001):
    for k in str(j):
        counting_num[k] += 1
print('0:%s개, 1:%s개, 2:%s개, 3:%s개, 4:%s개, 5:%s개, 6:%s개, 7:%s개, 8:%s개, 9:%s개' % tuple(counting_num.values()))

2019/05/18 10:58

최상혁

for i in range(0,10):
    print(i,':',end=' ')
    print(str(list(range(1,1001))).count(str(i)))

2019/06/14 11:36

wallace

#include <stdio.h>

void cnt_number(int number[], int left, int right) {
    int i, j, rest;
    for (i = left; i <= right; i++) {
        for (j = i; j != 0; ) {
            rest = j % 10;
            number[rest]++;
            j /= 10;
        }
    }
}

int main(void) {
    int number[10] = { 0, };
    cnt_number(number, 1, 1000);
    int i;
    for (i = 0; i < 10; i++)
        printf("%d: %d개\n", i, number[i]);
    return 0;
}

2019/06/16 16:36

박규석

data = [0 for i in range(10)]

for i in range(1, 1000 + 1):
    for j in str(i):
        data[int(j)] += 1


for j in range(10):
    print(j, data[j])

2019/06/21 12:37

파이썬주니어

a=0
b=0
c=0
d=0
e=0
f=0
g=0
h=0
j=0
k=0

for i in range ( 1,1001,1):
    for t in str(i):
        if ( 0 == int(t)):
            a=a+1
        elif( 1 == int(t)):
            b=b+1
        elif( 2 == int(t)):
            c=c+1
        elif( 3 == int(t)):
            d=d+1
        elif( 4 == int(t)):
            e=e+1
        elif( 5 == int(t)):
            f=f+1
        elif( 6 == int(t)):
            g=g+1
        elif( 7 == int(t)):
            h=h+1
        elif( 8 == int(t)):
            j=j+1
        elif( 9 == int(t)):
            k=k+1
print(a,b,c,d,e,f,g,h,j,k)

2019/06/23 16:50

나는인기쟁이

1~1000에서 각 숫자의 개수 구하기

list_tot = []

for i in range(1,101): for j in list(str(i)): list_tot.append(j)

print(list_tot)

print(list_tot.count('1'))

for k in range(0,10): k = str(k) tot = list_tot.count(k) # print(tot) print("%s의 갯수 : %s " % (k, tot))

2019/06/27 14:06

SeongMin Hwang

파이썬 3.7.3입니다. 1부터 1000까지의 숫자를 쪼갠 후 0부터 9까지의 개수를 셌습니다.

num = []        
for i in range(1, 1001):
    i=str(i)                
    num.append(i)           
num = list(''.join(num))    

i=-1
while i<9:
    i += 1
    print(i, ':', num.count(str(i)),'개') 

2019/06/30 21:04

eeh

```{.python}

```for i in range(0,10): print(str(list(range(1, 1001))).count('%d'%i))

2019/07/03 14:01

문기훈

public class Counting {
    public static void main(String[] args) {
        int n, a, b, c, d;
        System.out.println("1000까지 스타트!");
        count sw = new count();
        for (n = 1; n <= 1000; n++) {
            if(n<1000&&n>=100) {
                a = n % 10;
                b = n % 100;
                b = b / 10;
                c = n / 100;
                sw.count(a);
                sw.count(b);
                sw.count(c);
            }
            else if(n<100&&n>=10){
                a=n%10;//9
                b=n%100;
                b=n/10;// 9
                sw.count(a);
                sw.count(b);
            }
            else if(n==1000)
            {
                a=0;
                b=0;
                c=0;
                d=1;
                sw.count(a);
                sw.count(b);
                sw.count(c);
                sw.count(d);
            }
            else{
                a=n%10;
                sw.count(a);
            }
        }
        sw.sum();
    }
}
class count{
    public static int a1=0,a2=0,a3=0,a4=0,a5=0,a6=0,a7=0,a8=0,a9=0,a0=0;
    public void count(int x) {
        switch (x) {
            case 0:
                a0 = a0 + 1;
                break;
            case 1:
                a1 = a1 + 1;
                break;
            case 2:
                a2 = a2 + 1;
                break;
            case 3:
                a3 = a3 + 1;
                break;
            case 4:
                a4 = a4 + 1;
                break;
            case 5:
                a5 = a5 + 1;
                break;
            case 6:
                a6 = a6 + 1;
                break;
            case 7:
                a7 = a7 + 1;
                break;
            case 8:
                a8 = a8 + 1;
                break;
            case 9:
                a9 = a9 + 1;
                break;
            default:
                break;
        }
    }
        public void sum()
        {
            System.out.println("0의 갯수:"+a0);
            System.out.println("1의 갯수:"+a1);
            System.out.println("2의 갯수:"+a2);
            System.out.println("3의 갯수:"+a3);
            System.out.println("4의 갯수:"+a4);
            System.out.println("5의 갯수:"+a5);
            System.out.println("6의 갯수:"+a6);
            System.out.println("7의 갯수:"+a7);
            System.out.println("8의 갯수:"+a8);
            System.out.println("9의 갯수:"+a9);
        }
}

자바로 풀었어요! 정답은:0은 1921은 301 나머지는 300~

2019/07/04 00:18

Lanok

dic = {}
for i in range(1,1001):
    t1 = str(i)
    for j in range(len(t1)):
        t2 = t1[j]
        if t2 in dic:
            dic[t2] += 1
        else:
            dic[t2] = 1
result = list(dic.items())
result.sort()

for i in range(len(result)):
    print(str(result[i][0]) + ":" + str(result[i][1]) + "개")

2019/07/05 18:35

최은미

a = list(range(1, 1001))    # 1~1000까지의 정수 리스트 a 생성
b = ''.join(map(str, a))    # 리스트 a의 요소들을 문자열로 바꾼 뒤 공백을 기준으로 join

for i in range(0, 10):      # 0부터 9까지 각각의 숫자 카운트값 출력
    for n in str(i):
        print(b.count(n))

2019/07/06 15:12

종이

dic = {'0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0}

for i in range(1, 1001): for j in str(i): dic[j] = dic.get(j) + 1

print(dic)

2019/07/13 23:52

Shane Lee

import java.util.Arrays;

public class numCount {

    public static void main(String[] args) {
        int start=1, range=1000, comma=0;

        int[] count = new int[10];

        Arrays.fill(count, 0);

        for (int i= start; i<(start+range); i++) {
            String str = Integer.toString(i);
            for(int j=0; j<str.length(); j++) {
                count[Integer.parseInt(str.substring(j, j+1))]++;
            }
        }       

        for(int i=0; i<count.length; i++) {
            if(count[i]!=0) {
                if(comma>0) {
                    System.out.print(", ");
                }
                System.out.print(i + " : " + count[i] + "개");
                comma++;
            }           
        }
    }
}

char 문자형변환을 이용한 수정

public class numCount {

    public static void main(String[] args) {
        int start=1, range=1000, comma=0;

        int[] count = new int[10];

        for(int i = 0; i<count.length; i++) {
            count[i] = 0;
        }

        for (int i= start; i<(start+range); i++) {
            String str = Integer.toString(i);
            for(int j=0; j<str.length(); j++) {
                count[str.charAt(j)-'0']++;
            }
        }

        for(int i=0; i<count.length; i++) {
            if(count[i]!=0) {
                if(comma>0) {
                    System.out.print(", ");
                }
                System.out.print(i + " : " + count[i] + "개");
                comma++;
            }           
        }
    }
}

2019/07/22 21:45

김준성

dic={i:0 for i in range(0,10)}
for q in range(1,1001):
    for w in str(q):
        dic[int(w)]+=1
print(dic)

2019/07/23 12:24

유선종

n0 = n1 = n2 = n3 = n4 = n5 =n6 = n7 = n8 =n9=0
for i in range(1,1001):
    i = list(str(i))
    n0 += i.count("0")
    n1 += i.count("1")
    n2 += i.count("2")
    n3 += i.count("3")
    n4 += i.count("4")
    n5 += i.count("5")
    n6 += i.count("6")
    n7 += i.count("7")
    n8 += i.count("8")
    n9 += i.count("9")
print(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9)

2019/07/23 15:27

YAPING CAO

python

result = dict(zip([str(i) for i in range(0,10)],[0]*10))
for i in range(1,1001):
    for k in range(0,10):
        if str(k) in str(i):
            result[str(k)] += str(i).count(str(k))
print(result)

2019/07/29 16:17

apriori

def count():

string=""
for i in range(1, 1001):
    string += str(i)
return(string)

string=count()

c0=string.count("0") c1=string.count("1") c2=string.count("2") c3=string.count("3") c4=string.count("4") c5=string.count("5") c6=string.count("6") c7=string.count("7") c8=string.count("8") c9=string.count("9")

print(c0,c1,c2,c3,c4,c5,c6,c7,c8,c9)

2019/07/31 14:01

Hwain Choi

number = [0,0,0,0,0,0,0,0,0,0]
for x in range (1,1001):
    for y in str(x):
        number[int(y)] = number[int(y)] + 1

2019/08/02 23:48

yh

python 3.7

num =[ 0 for i in range(10)]

for i in range(1,1001):
    for x in str(i):
        num[int(x)]+=1

print(num)

2019/08/04 20:12

Sechi

a0=a1=a2=a3=a4=a5=a6=a7=a8=a9=0
for i in range(1,1001,1):
    a0=a0+str(i).count('0')
    a1=a1+str(i).count('1')
    a2=a2+str(i).count('2')
    a3=a3+str(i).count('3')
    a4=a4+str(i).count('4')
    a5=a5+str(i).count('5')
    a6=a6+str(i).count('6')
    a7=a7+str(i).count('7')
    a8=a8+str(i).count('8')
    a9=a9+str(i).count('9')
print("0:{0} 1:{1} 2:{2} 3:{3} 4:{4} 5:{5} 6:{6} 7:{7} 8:{8} 9:{9}".format(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9))

2019/08/06 07:47

박재욱

def prob(n1,n2):
    num=[0 for i in range(10)]
    #print(num, type(num))
    for i in range(n1,n2):
        for l in str(i):
            num[int(l)]+=1
    printArray(num)

def printArray(arr):
    for i in range(len(arr)):
        print('{0}:{1}'.format(i,arr[i]), end=' ')

2019/08/07 10:18

최재학

파이썬 초보입니다.. 그냥 올려본거에요

alist = []
blist = []

print("숫자 개수세기 프로그램입니다. 1~9999 범위 내에서 작동 가능합니다")
start = int(input("start number: "))
end = int(input("end number: "))

for x in range(start, end+1) :
    y = str(x)
    alist.append(y)

for x in alist :
    if len(x) == 1:

        blist.append(x[0])
    elif len(x) == 2:
        blist.append(x[0])
        blist.append(x[1])
    elif len(x) == 3:
        blist.append(x[0])
        blist.append(x[1])
        blist.append(x[2])
    elif len(x) == 4:
        blist.append(x[0])
        blist.append(x[1])
        blist.append(x[2])
        blist.append(x[3])
    else:
        print("Out of number")

txt= " 0은: {}번 나왔다.\n 1은: {}번 나왔다.\n 2는: {}번 나왔다.\n 3은: {}번 나왔다.\n 4는: {}번 나왔다.\n 5는: {}번 나왔다.\n 6은: {}번 나왔다.\n 7은: {}번 나왔다.\n 8은: {}번 나왔다.\n 9는: {}번 나왔다."

zero = blist.count('0')
one = blist.count('1')
two = blist.count('2')
three =blist.count('3')
four = blist.count('4')
five = blist.count('5')
six = blist.count('6')
seven = blist.count('7')
eight =blist.count('8')
nine =blist.count('9')

print(txt.format(zero, one, two, three, four, five, six, seven, eight, nine))

2019/08/07 21:15

Minseok Choi

C#으로 작성했습니다.

    static void Main(string[] args)
    {
        int N = 10, k;
        int[] sum = new int[10];

        for (int i = 1; i <= N; i++) 
        {
            k = i;
            while (k > 0)
            {
                sum[k % 10] += 1;
                k /= 10;
            }
        }
        foreach(int i in sum)
            Console.WriteLine(i);
    }

2019/08/21 10:43

류원형

d = dict()
for i in range(1, 1001):
    for n in str(i):
        if int(n) in d:
            d[int(n)]+=1
        else:
            d[int(n)]=1

for k in d:
    print('{} : {} 개' .format(str(k), str(d[k])))

2019/08/22 16:53

돔돔

zero=0;one=0;two=0;three=0;four=0;five=0;six=0;seven=0;eight=0;nine=0
i = input().split('~')
f = int(i[0]); l = int(i[1])
for i in range(f, l+1):
    i = str(i)
    zero+=i.count('0'); one+=i.count('1'); two+=i.count('2'); three+=i.count('3'); four+=i.count('4')
    five+=i.count('5'); six+=i.count('6'); seven+=i.count('7'); eight+=i.count('8'); nine+=i.count('9')
print(zero,one,two,three,four,five,six,seven,eight,nine)

2019/08/27 14:17

이명운

count=[i for i in range (0,10)]
for a in range(0,1001):
    for b in list(str(a)):
        count[int(b)-1]+=1


print (count)


2019/08/29 14:04

Cosu

def countNum(_input):
    count=[0]*(10)
    print (count)
    for a in range(0,_input+1):
        for b in list(str(a)):
            count[int(b)]+=1
    return count


print (countNum(1000))


2019/08/29 15:14

Cosu

def counter(intNum, intStart, intEnd):
    return str([x for x in range(int(intStart), int(intEnd))]).count(str(intNum))

for itr in range(0, 10):
    print('%d :'%itr, counter(itr, 1, 1001))

2019/09/05 16:55

Dreaming Pug

result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for j in range(1, 1001): for x in str(j): result[int(x)] += 1

print(result)

2019/09/09 13:51

김민규

PHP

$arr = [];
$str = implode(range(1, 1000));
for ($i = 0, $c = strlen($str); $i < $c; $i++) {
    if (!isset($arr[$str[$i]])) $arr[$str[$i]] = 0;
    $arr[$str[$i]]++;
}
ksort($arr);
$result = $arr;

print_r($result); // [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

2019/09/10 17:47

d124412

answer = {}
for i in range(1, 1001):
    for key in str(i):
        answer.setdefault(key, 0)
        answer[key] += 1
print(answer)

파이썬3입니다.

2019/09/11 22:00

JayK

s = []
n = 0

for a in range(1, 1001):
    sa = str(a)
    for st in sa:
        s.append(st)

while n < 10:
    print(str(n) + '의 개수 : ' + str(s.count(str(n))))
    n += 1

2019/09/19 14:22

형수김

count = [0] * 10
for i in range(1, 1001):
    for j in str(i):
        count[int(j)] = count[int(j)] + 1

print(count)

2019/09/22 16:13

박주현

number_list = list(range(1, 1001))
kk = ''
n = 0
for n in range(0, 1000) :
    kk = kk + str(number_list[n])
m = 0
for m in range(0, 10) :
    s = kk.count("%d" %m)
    print("%d : %d"%(m, s))

결과

0 : 192 1 : 301 2 : 300 3 : 300 4 : 300 5 : 300 6 : 300 7 : 300 8 : 300 9 : 300

2019/09/24 15:22

GG

int b[] = new int[10];

  for(int i=1; i <=1000;i++){
  b[i%10]++;
  if(i>=10) b[(i/10)%10]++;
  if(i>=100) b[(i/100)%10]++;
  if(i==1000) b[1]++;
}
System.out.println(Arrays.toString(b));

2019/09/28 02:38

Reviday

for i in range(0,10):
    count = 0
    print(i,' : ',str(list(x for x in range(1,1001))).count(str(i)),'개',end = ', ' )

2019/09/30 14:34

nhoeal

result = []

for i in range(1,1001):
    tmp=list(str(i))
    result += tmp
set_char = sorted(set(result))
for char in set_char:
   print("{}는 {}개 입니다.".format(char,result.count(char)))

2019/10/05 23:16

semipooh


for i in range(10):
    print('%s :' %i ,str([i for i in range(1, 1001)]).count(str(i)))

2019/10/06 16:13

후눈


temp = [0,0,0,0,0,0,0,0,0,0]

for num in range(1,1001):
    while num > 0:
        index = int(num%10)
        temp[index] += 1
        num //= 10

for i in range(0,10):
    print(temp[i])

2019/10/14 18:50

sidedoor

    li_a = []

    for i in range(1,1001):
        li_a.append(list(str(i)))

    for i in range(10):
        print(i, ' : ', str(li_a).count(str(i)))

2019/10/17 10:28

dj kim

import java.util.Arrays;

public class number {

    public static void main(String[] args) {

        int[] number = new int[1000];

        for (int j = 0; j < number.length; j++){
            number[j] = j;
        }

        String result = Arrays.toString(number).replaceAll("[^0-9]", "");

        int count0 = 0;
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        int count4 = 0;
        int count5 = 0;
        int count6 = 0;
        int count7 = 0;
        int count8 = 0;
        int count9 = 0;

        for (int i = 0; i < result.length(); i++) {
            switch (result.charAt(i)) {
            case '0':
                count0 ++;
                break;
            case '1':
                count1 ++;
                break;
            case '2':
                count2 ++;
                break;
            case '3':
                count3 ++;
                break;
            case '4':
                count4 ++;
                break;
            case '5':
                count5 ++;
                break;
            case '6':
                count6 ++;
                break;
            case '7':
                count7 ++;
                break;
            case '8':
                count8 ++;
                break;
            case '9':
                count9 ++;
                break;
            }
        }

        System.out.println("숫자 0 은(는) " + count0 + "개 있습니다.");
        System.out.println("숫자 1 은(는) " + count1 + "개 있습니다.");
        System.out.println("숫자 2 은(는) " + count2 + "개 있습니다.");
        System.out.println("숫자 3 은(는) " + count3 + "개 있습니다.");
        System.out.println("숫자 4 은(는) " + count4 + "개 있습니다.");
        System.out.println("숫자 5 은(는) " + count5 + "개 있습니다.");
        System.out.println("숫자 6 은(는) " + count6 + "개 있습니다.");
        System.out.println("숫자 7 은(는) " + count7 + "개 있습니다.");
        System.out.println("숫자 8 은(는) " + count8 + "개 있습니다.");
        System.out.println("숫자 9 은(는) " + count9 + "개 있습니다.");

    }
}

2019/10/22 16:26

왕선홍

a = str(list(range(10, 16)))
for i in range(0, 10):
    print(i , ' : ' , a.count(str(i)))

2019/10/23 13:13

jawoongku

python 3

a = str([[xx for xx in str(x)] for x in range(1, 1001)])
for i in range(0, 10):
    print('%d:'%i, a.count(str(i)))   

0: 192
1: 301
2: 300
3: 300
4: 300
5: 300
6: 300
7: 300
8: 300
9: 300

2019/10/23 17:06

조현우

list_number=[]
for number in range(1, 1001):
    str_number = ','.join(str(number))  # 각 숫자 사이에 ',' 삽입
    new_number = str_number.split(',')  # ','를 기준으로 split
    for i in new_number:
        list_number.append(i)           
for x in range(0, 10):
    print(x, ':', list_number.count(str(x)))

배운지 일주일정도라 허접합니다. 이해바랍니다. 5, 6행을 넣은 이유는 그냥 new_number를 리스트에 넣었더니 리스트안에 리스트로 만들어져서 리스트안의 요소를 하나씩 거내어 리스트로 넣기위해서 입니다.

2019/11/04 10:35

Purple_Ryu

파이썬으로 작성했습니다.

import collections

def split(x): # str로 변환한 숫자를 개별 숫자로 나누는 함수를 만들었습니다.
    for i in range(len(x)): #숫자의 크기에 따라서 인덱스 번호를 달리 줄 수 있도록 len(x)과 range()를 중첩했습니다.
        x[i]
    return x[i]    

num_1000=list(map(str,list(range(1,1001)))) # 1~1000까지 숫자를 만들고 map 함수로 str로 변환 인덱스로 나눌 수 있게함
num_frequency=sorted(list(map(lambda x: split(x) ,num_1000))) #실질적으로 숫자를 나누고  종류별로 나누게 만들었음.
char_dict = collections.Counter(num_frequency) # collections 내장 함수인 Counter를 이용하여 종류별로 갯수를 셌음.
print(char_dict)

2019/11/07 12:37

data big

package practiceLv1;
public class 각숫자의개수구하기 {

    public static void main(String[] args) {
        int[] numbers = new int[1000];
        for(int i = 0; i<1000; i++) {
            numbers[i] = i+1;
        }
        String numbers_list[] = new String[numbers.length];
        for(int j = 0; j<numbers.length; j++) {
            numbers_list[j] = String.valueOf(numbers[j]);
        }
        int[] n = new int[10];
        for(int k = 0; k<numbers.length; k++) {
            String numbers_list2[] = numbers_list[k].split("");
            for(int l=0; l<numbers_list2.length; l++) {
            if(numbers_list2[l].contains("0")) {
                n[0]+=1;
            }
            if(numbers_list2[l].contains("1")) {
                n[1]+=1;
            }
            if(numbers_list2[l].contains("2")) {
                n[2]+=1;
            }
            if(numbers_list2[l].contains("3")) {
                n[3]+=1;
            }
            if(numbers_list2[l].contains("4")) {
                n[4]+=1;
            }
            if(numbers_list2[l].contains("5")) {
                n[5]+=1;
            }
            if(numbers_list2[l].contains("6")) {
                n[6]+=1;
            }
            if(numbers_list2[l].contains("7")) {
                n[7]+=1;
            }
            if(numbers_list2[l].contains("8")) {
                n[8]+=1;
            }
            if(numbers_list2[l].contains("9")) {
                n[9]+=1;
            }
            }
        }
        System.out.println("0:"+n[0]+"개");
        System.out.println("1:"+n[1]+"개");
        System.out.println("2:"+n[2]+"개");
        System.out.println("3:"+n[3]+"개");
        System.out.println("4:"+n[4]+"개");
        System.out.println("5:"+n[5]+"개");
        System.out.println("6:"+n[6]+"개");
        System.out.println("7:"+n[7]+"개");
        System.out.println("8:"+n[8]+"개");
        System.out.println("9:"+n[9]+"개");
        /*
          int[] box = new int[10];

    for (int i = 1; i <= 1000; 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]++;//천의 자리
    }
    System.out.println(Arrays.toString(box));
         */
    }

}

2019/11/07 21:54

big Ko

let count = {};
for (let i = 0; i < 10; i++) count[i] = 0;

for (let i = 1; i < 1001; i++) {
  let temp = String(i);
  for (let j = 0; j < temp.length; j++) {
    count[temp[j]] += 1;
  }
}
console.log(count);

{ '0': 192, '1': 301, '2': 300, '3': 300, '4': 300, '5': 300, '6': 300, '7': 300, '8': 300, '9': 300 }

2019/11/08 02:48

GyuHo Han

파이썬 3.6 입니다

def count_each_number(n, m):
    numbers = list(range(n, m + 1))
    numbers_to_count = range(0, 10)
    for i in numbers_to_count:
        print(f" {i}: {str(numbers).count(str(i))}")

print(count_each_number(1, 1000))

2019/11/22 12:48

vkospi

list = [0,0,0,0,0,0,0,0,0,0]
for i in range(1,1000+1):
    for j in str(i):
        list[int(j)]+=1


for x in range(10):
    print("%d 은(는) %d개 입니다." %(x,list[x]))

2019/11/24 16:57

Kong

print [sum([[a for a in str(x)].count(str(i)) for x in range(1,1000+1)]) for i in range(0,10)]

한줄로 짜기 연습중이어서 한줄로 짜봣어요

답은 [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

2019/11/26 11:37

오오옹

파이썬입니다. 고수분들이 정말 많네요. 배워갑니다.

n = int(input('숫자를 입력하세요.'))

count = {x: 0 for x in range(0,10)}

for x in range(0,n):
  for y in str(x):
    count[int(y)] +=1

print(count)

2019/12/19 18:29

Sean

파이썬으로 작성했습니다. 입력값을 Range로 받아 텍스트로 바꾸고 내장함수인 count를 이용하여, 문자열로 된 리스트 내에 1,2,3... 등 각각의 자연수 갯수를 카운팅합니다.

a=int(input())
b=int(input())
c=list(range(a,b+1))
print("0의 갯수는 %d" %str(c).count('0'))
print("1의 갯수는 %d" %str(c).count('1'))
print("2의 갯수는 %d" %str(c).count('2'))
print("3의 갯수는 %d" %str(c).count('3'))
print("4의 갯수는 %d" %str(c).count('4'))
print("5의 갯수는 %d" %str(c).count('5'))
print("6의 갯수는 %d" %str(c).count('6'))
print("7의 갯수는 %d" %str(c).count('7'))
print("8의 갯수는 %d" %str(c).count('8'))
print("9의 갯수는 %d" %str(c).count('9'))

2019/12/20 06:49

김동석

int COunt_Each_Num()
{
int result[10] ={0,0,0,0,0,0,0,0,0,0};
for(int T=0;T<10;T++)
{
for(int S=0;S<10<S++)
{
for(int F=0;F<10;F++)
{
result[F]++;
result[S]++;
result[T]++;
}
}
}

return result;
}

2019/12/22 18:22

Anderson

n=0
while n<10:
    cn=str(n)
    print(str(n)+":",str(str(list(range(1,1001))).count(cn))+"개")
    n+=1

2019/12/27 00:38

박시원

dic = {
    '0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0
}

tmplist1 = [str(i) for i in range(1,1001)] # 왜냐하면 str이 iterable이라 다루기 쉬우니까..
print(tmplist1)

for i in tmplist1:
    if len(i) == 1:
        dic[i] = dic[i] + 1
    else :
        for k in i:
            dic[k] += 1
print(dic)

2020/01/06 17:12

H

num = range(10,16)
numLst = [i for i in num]
print(numLst)

cntLst = []
for i in numLst:
    a = i//10
    cntLst.append(a)
    b = i%10
    cntLst.append(b)

for i in range(6):
    print("of %d: %d"%(i,cntLst.count(i)))

2020/01/10 17:17

Jung Marco

a = []

for i in list(range(1,1001)):
    b = list(str(i))
    a += b

c = list(map(int, a))

for i in range(10):
    print('숫자 {}은 {}개'.format(i, c.count(i)))

2020/01/14 23:17

김희준

a = []

for i in list(range(1,1001)):
    b = list(str(i))
    a += b

for i in range(10):
    print('숫자 {}은 {}개'.format(i, a.count(str(i))))

2020/01/14 23:24

김희준

Nlist, Nlistmain = list(), list()
for i in range(1,1001):
    Ntemporary = str(i)
    for j in range(len(Ntemporary)):
        Nlist.append(Ntemporary[j])

for i in range(10):
    Nlistmain.append(Nlist.count(f'{i}'))
    print(f'{i}: {Nlist.count(f"{i}")}')

2020/01/22 16:22

BlakeLee

파이썬 3입니다

각 숫자를 문자열로 바꿔서 숫자를 셌습니다.

number_count = 10*[0]

for n in range(1, 1001):
    for i in str(n):
        number_count[int(i)] += 1

for i in range(len(number_count)):
    print('{}:{}개'.format(i, number_count[i]), end=', ')

2020/01/26 15:45

우재용

for i in range(10):

x=0

for j in range(1,1001):

    a = str(j)

    b = a.count(str(i))

    x=x+b

print (i,x)

2020/01/28 00:29

HyukHoon Kim

a, b = map(int, input().split(' '))
num = list(range(a, b+1)) # 더할 숫자를을 리스트로 만듬
c = 0 
for i in num:
    i_splited = list(str(i)) #정수형을 문자열로 바꿔준 뒤 리스트 함수를 사용 (list(str(11))) = ['1', '1']
    for j in i_splited:
        c += int(j) #for문 한번 더 사용하여 모두 더하여 줌

print(c)


2020/01/31 17:01

Karinist xo

def digit_count(x,y):
    d={ x:0 for x in range(0,10) }

    for n in range(x, y+1):
        for x in str(n):
            d[int(x)] += 1
    print(d)
    return d

# 1~1000 범위내 모든 digitnumber count
digit_count(1,1000)

2020/02/03 19:20

maluchi

sum = 0 sum1 = 0 sum2 = 0 sum3 = 0 sum4 = 0 sum5 = 0 sum6 = 0 sum7 = 0 sum8 = 0 sum9 = 0 for i in range(1, 1001): i = str(i) A = i.count('1') sum += A B = i.count('2') sum1 += B C = i.count('3') sum2 += C D = i.count('4') sum3 += D E = i.count('5') sum4 += E F = i.count('6') sum5 += F G = i.count('7') sum6 += G H = i.count('8') sum7 += H I = i.count('9') sum8 += I J = i.count('0') sum9 += J print(sum, sum1, sum2, sum3, sum4, sum5, sum6, sum7, sum8, sum9)

2020/02/13 16:34

이국성

a = list(range(10,16))
c = list(b for b in str(a))
print("0: ", c.count('0'))
print("1: ", c.count('1'))
print("2: ", c.count('2'))
print("3: ", c.count('3'))
print("4: ", c.count('4'))
print("5: ", c.count('5'))

2020/02/16 22:23

Junghan Shin

nums = [str(x) for x in range(1,1001)] # 1부터1000까지 문자열 형태로 저장
nums2 = [] 
for i in range(1000): # nums의 원소인 문자열을 뜯어서 저장
    len_num = len(nums[i])
    for j in range(len_num):
        nums2.append(nums[i][j])

for i in range(10):
    print("{}:{}개".format(i, nums2.count(str(i))), end=' ')

2020/02/17 01:45

카레맛카레

answer = {}
for i in range(10):
    answer[i] = 0

for i in range(1, 1001):
    for k in [int(j) for j in str(i)]:
        answer[k] += 1
print(answer)

2020/02/17 11:18

KMH

    class Program
    {


        static void Main(string[] args)
        {
            int[] re_arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 
            string arr = "10,11,12,13,14,15";
            string[] result = arr.Split(new char[] { ',' });
            for (int i = 0; i< result.Length; i++)
            {
                foreach(char a in result[i])
                {
                    string b = a.ToString();
                    int count = Int32.Parse(b);
                    re_arr[count] += 1; 
                 }       
            }
            for (int j =0; j<re_arr.Length; j++)
            {
                Console.WriteLine("{0}는 {1}개가 있습니다.",j,re_arr[j]);
            }
        }
    }

2020/02/21 14:03

서주혁

#1to1000.py


for i in range(10):
    count=0 #세는 수가 바뀔때마다 초기화
    for j in range(1,1001):
         count += str(j).count(str(i))

    print("{0}:{1}개".format(i,count))

2020/02/28 16:52

황예진

파이썬 3.7 딕셔너리를 이용하면 더 좋아겠네요

data = [0] * 10
for d in range(1, 1001):
    for i, v in enumerate(str(d)):
        data[int(v)] += 1
print(data)

2020/03/03 18:48

우제훈

def num_count(number):
    import re
    p=re.compile("\d")
    chest=[]
    result={}
    for i in range(1, number+1):
        temp=p.findall(str(i))
        for j in temp:
            chest.append(j)
    for i in range(10):
        result[i]=str(chest.count('%d'%i))
    return result
print(num_count(1000))

2020/03/04 23:37

Caplexian _

sum=[0,0,0,0,0,0,0,0,0,0]

for i in range (1, 1001):
a=str(i)
a_len=len(a)
for j in range (0,a_len):
sum[int(a[j])]=sum[int(a[j])]+1

for i in range (0,10):
print (i,'->',sum[i])

2020/03/05 11:18

Buckshot

#Number Counter by Python
list_1=[]
list_2=[]

for i in range(1,1001):
    s=str(i)
    s=" ".join(s)
    s=s.split(" ")
    list_1.extend(s)

for j in range(0,10):
    k=str(j)
    num=list_1.count(k)
    list_2.append(f'{k}: {num}')

print(list_2)

#Answer: ['0: 192', '1: 301', '2: 300', '3: 300', '4: 300', '5: 300', '6: 300', '7: 300', '8: 300', '9: 300']

2020/03/10 20:57

여종헌

num_store = []

for i in range(1,1001):
    num_store.append(str(i))

#0~1000까지의 숫자 생성

for i in range(10):
    print(i,"은"+":",''.join(num_store).count(str(i)),"개")

#갯수 카운트

2020/03/12 16:10

안재길

#include <iostream>
#include <string>
using namespace std;
//EX)
/*10 = 1, 0
  11 = 1, 1
  12 = 1, 2
  13 = 1, 3
  14 = 1, 4
  15 = 1, 5

그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개
*/


//답 0:192개 1:301개 2:300개 3:300개 4:300개 5:300개 6:300개 7:300개 8:300개 9:300개
void Func(int s, int e) {
    int arr[10] = { 0, };

    for (int i = s; i <= e; i++) {
        cout << i << " = ";
        string str = to_string(i);
        for (int j = 0; j < str.length(); j++) { //숫자가 "12"라면, 길이는 2 (0~1)까지반복
            for (int k = 0; k < 10; k++) {//먼저 첫번째 요소를 0-9까지 매칭되는것을 검사
                if (str[j] - '0' == k) {//매칭 되는 숫자를 찾은경우
                    arr[k] = ++arr[k];
                    if (j == str.length() - 1) { cout << k << endl; }
                    else { cout << k << ","; }
                }
            }
        }
    }
    cout << endl;
    for (int i = 0; i < 10; i++) {
        if (arr[i] > 0) {
            cout << i << ":" << arr[i] << "개 ";
        }
    }
    cout << endl;
}

int main() {
    Func(1, 1000);
}

2020/03/20 13:50

++C

파이썬 3.7.6 입니다. 1부터 1000까지의 숫자를 모두 문자열로 이어붙이고, count 를 이용해서 각 숫자의 개수를 센 다음 리스트로 출력합니다.

target_list=(''.join([str(x) for x in range(1,1000+1)]))
print([target_list.count(str(x)) for x in range(0,10)])
# 출력 결과 : [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

2020/03/22 09:35

jjojjo

result = []
for x in range(1, 1001):
    y = [int(n) for n in str(x)]
    for item in y:
        result.append(item)
        li =[]
        for i in range(0,10):
            z={i:result.count(i)}
            li.append(z)
li

2020/03/24 18:23

Shio Joo

f=[0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    l=list(str(i))
    for i in l:
        for k in range(10):
            if str(k)==i:
                f[k]+=1
            else:
                pass
print(f)
'''
파이썬 입니다.
'''

2020/03/28 20:08

di figo

num_0 = 0
num_1 = 0
num_2 = 0
num_3 = 0
num_4 = 0
num_5 = 0
num_6 = 0
num_7 = 0
num_8 = 0
num_9 = 0

for i in range(1,1001):
    num_0 += str(i).count('0')
    num_1 += str(i).count('1')
    num_2 += str(i).count('2')
    num_3 += str(i).count('3')
    num_4 += str(i).count('4')
    num_5 += str(i).count('5')
    num_6 += str(i).count('6')
    num_7 += str(i).count('7')
    num_8 += str(i).count('8')
    num_9 += str(i).count('9')

print('0의 개수: %s,1의 개수: %s,2의 개수: %s,3의 개수: %s,4의 개수: %s,5의 개수: %s,6의 개수: %s,7의 개수: %s,8의 개수: %s,9의 개수: %s,' %(num_0,num_1,num_2,num_3,num_4,num_5,num_6,num_7,num_8,num_9))
num0_9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for n in range(1,1001):
    for i in range(10):
        x = str(n).count(str(i))
        if x > 0:
            num0_9[i] = num0_9[i] + x
print(num0_9)

파이썬 노가다 버전과 정리한 버전입니다.

2020/04/02 16:09

기둘비

a=int(input())
b=int(input())
c=list(range(a,b))
print("1:%d",%str(c).count('1')
print("2:%d",%str(c).count('2')
print("3:%d",%str(c).count('3')
print("4:%d",%str(c).count('4')
print("5:%d",%str(c).count('5')
print("6:%d",%str(c).count('6')
print("7:%d",%str(c).count('7')
print("8:%d",%str(c).count('8')
print("9:%d",%str(c).count('9')

2020/04/02 21:41

Dongsuk Kim

public class sum_one_to_thousand {

    public static void main(String[] args) {

        String temp = "";

        int zero_count = 0;
        int one_count = 0;
        int two_count = 0;
        int three_count = 0;
        int four_count = 0;
        int five_count = 0;
        int six_count = 0;
        int seven_count = 0;
        int eight_count = 0;
        int nine_count = 0;

        for (int i = 1; i<=1000; i++) {
            temp = temp.concat(Integer.toString(i));
        }

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

            if (temp.charAt(a)=='0') {
                zero_count++;
            }

            else if (temp.charAt(a)=='1') {
                one_count++;
            }

            else if (temp.charAt(a)=='2') {
                two_count++;
            }

            else if (temp.charAt(a)=='3') {
                three_count++;
            }

            else if (temp.charAt(a)=='4') {
                four_count++;
            }

            else if (temp.charAt(a)=='5') {
                five_count++;
            }

            else if (temp.charAt(a)=='6') {
                six_count++;
            }

            else if (temp.charAt(a)=='7') {
                seven_count++;
            }

            else if (temp.charAt(a)=='8') {
                eight_count++;
            }

            else if (temp.charAt(a)=='9') {
                nine_count++;
            }

            else{}
        }

        System.out.println(zero_count);
        System.out.println(one_count);
        System.out.println(two_count);
        System.out.println(three_count);
        System.out.println(four_count);
        System.out.println(five_count);
        System.out.println(six_count);
        System.out.println(seven_count);
        System.out.println(eight_count);
        System.out.println(nine_count);

    }

}

2020/04/15 15:33

smylere


for n in range(10):
    num=0
    for m in range(1,1001):
        s=str(m)
        num+=s.count(str(n))
    print('%s 의 갯수는 :'%n,num)

2020/04/21 23:52

양양짹짹

l = str("")
for x in range(1,1001):
    l += str(x)
for i in range(0,10):
    print('%d:%d개' % (i, l.count(str(i))), end=' ')

2020/04/24 14:29

YB Jung

c={'count_0':0,'count_1':0,'count_2':0,'count_3':0,'count_4':0,'count_5':0,'count_6':0,'count_7':0,'count_8':0,'count_9':0}

for k in range(1,1001) :
    b=str(k)
    for i in range(0,len(b)) :
        if b[i]=='0':
            c['count_0'] +=1
        elif b[i]=='1':
            c['count_1'] +=1
        elif b[i]=='2':
            c['count_2'] +=1
        elif b[i]=='3':
            c['count_3'] +=1
        elif b[i]=='4':
            c['count_4'] +=1
        elif b[i]=='5':
            c['count_5'] +=1
        elif b[i]=='6':
            c['count_6'] +=1
        elif b[i]=='7':
            c['count_7'] +=1
        elif b[i]=='8':
            c['count_8'] +=1
        elif b[i]=='9':
            c['count_9'] +=1

print(c)

2020/04/28 15:49

조윤재

파이썬입니다.

num = []
listing_num = []

def count_x(num_list, num):
    return num_list.count(num)

for x in range(1,1001):
    num.append(x)

for x in num:
    for i in str(x):
        listing_num.append(i)

for x in range(0,10):
    print(f"{x} : {count_x(list(map(int, listing_num)),x)}개")

2020/05/01 17:27

peca lee

public class Q105_00 {

    public static void main(String[] args) {
        int zero = 0;
        int one = 0;
        int two = 0;
        int three = 0;
        int four = 0;
        int five = 0;
        int six = 0;
        int seven = 0;
        int eight = 0;
        int nine = 0;
        StringBuffer input = new StringBuffer();
        for (int i = 1; i < 1001; i++) {
            input.append(Integer.toString(i));
        }
        String[] num = num.toString().split("");
        for (int i = 0; i < num.length; i++) {
            if (num[i].equals("0")) zero++;
            if (num[i].equals("1")) one++;
            if (num[i].equals("2")) two++;
            if (num[i].equals("3")) three++;
            if (num[i].equals("4")) four++;
            if (num[i].equals("5")) five++;
            if (num[i].equals("6")) six++;
            if (num[i].equals("7")) seven++;
            if (num[i].equals("8")) eight++;
            if (num[i].equals("9")) nine++;
        }
        System.out.printf("0은 %d번\n", zero);
        System.out.printf("1은 %d번\n", one);
        System.out.printf("2은 %d번\n", two);
        System.out.printf("3은 %d번\n", three);
        System.out.printf("4은 %d번\n", four);
        System.out.printf("5은 %d번\n", five);
        System.out.printf("6은 %d번\n", six);
        System.out.printf("7은 %d번\n", seven);
        System.out.printf("8은 %d번\n", eight);
        System.out.printf("9은 %d번\n", nine);
    }
}

1~1000까지 받아서 하나하나 쪼개서 구했습니다.

2020/05/05 12:59

Daniel Park

def count_num():
    string = "".join([str(i) for i in range(1, 1001)])
    return dict([(str(i), string.count(str(i))) for i in range(10)])

2020/05/06 20:03

김준혁

NUM_list = []

for x in range(10,16):
        NUM_list += list(str(x))


print(NUM_list)
for num in range(11):
    if str(num) in NUM_list:
        print(num,':',NUM_list.count(str(num)))
    else:
        pass

배열을 사용하지 않고 풀어보려했으나 쉽지않네요

2020/05/25 17:26

진)파이썬마스터

public class NumberIndex {

public int[] solution(int numbers) {


    int pNum = 0;


    int[] count = new int[10];


    for(int i=1;i<= numbers;i++) {
        int numlen = (int)(Math.log10(i));

        for(int j= numlen;j>=0;j--) {
            pNum = (int) (i/Math.pow(10, j));
            if(pNum>=10) {
                pNum = pNum%10;
            }
            //System.out.println(i);
            //System.out.println(pNum);
            count[pNum]++;
        }
        //pNum = i%10;
        //System.out.println(pNum);
        //count[pNum]++;

    }

    return count;
}

public static void main(String[] args) {

    int data = 1000;

    NumberIndex solution = new NumberIndex();

    for(int i=0;i<10;i++) {
        System.out.println(i+":" + solution.solution(data)[i]);
    }





}

}

2020/05/26 15:10

니클백

a = []
for i in range(1,1001):
    for num in str(i):
        a.append(num)

for i in range(10):
     print(i, a.count(str(i)))

2020/06/01 10:35

mir

number_counter = [0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    number_1 = i % 10
    number_counter[number_1] += 1
    if i >= 10:
        number_10 = (i // 10) % 10
        number_counter[number_10] += 1
    if i >= 100:
        number_100 = (i // 100) % 10
        number_counter[number_100] += 1
    if i == 1000:
        number_1000 = i // 1000
        number_counter[number_1000] += 1
for i in range(10):
    print(i,end="")
    print(":",end="")
    print(number_counter[i],end="")
    print("개,",end=" ")
print("")

2020/06/02 21:59

2 spear

d=[]

for a in range(1,1001):
    for b in str(a):
        c = int(b)
        e = d.append(c)


def result(number):
    f = d.count(number)
    return f

for i in range(0,10):
    g = result(i)
    print(f"{i}={g}개")

파이썬 배운지 2주 되었는데, 실력이 늘었으면 해서 안 보고 열심히 해봤습니다!

먼저 숫자를 리스트화 한다음에 문자열로 바꿔서 다시 리스트로 만들었구요. 그리고나서 리스트의 카운터 기능을 이용해서 세어봤습니다.

2020/06/06 18:11

Taek Kor_

a = {0:0,1:0,2:0,3: 0,4: 0,5:0,6:0,7:0,8:0,9:0}
for i in range(1, 1001):
    while i!=0:
        a[i%10] += 1
        i=i//10

print(a)

2020/06/17 17:45

YSM

{j:sum([list(str(i)).count((str(j))) for i in range(1,1001) ]) for j in range(10)}

결과 {0: 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300}

2020/06/25 17:36

이상해라


public class split {

    public static int[] squeze(int number){

        int[] result = new int[10]; 
        int a=0;
        int b=0;
        int c=0;

        if(number==1000)
        {
            result[0] = 3;
            result[1] = 1;
            return result;
        }
        else if(100<=number&& number<1000){
        a = number/100;
        b = (number -(a*100))/10;
        c = number - (a*100 + b*10);

        result[a]++;
        result[b]++;
        result[c]++;
        }
        else if(number>=10 && number<100)
        {
            b = number/10;
            c = number-b*10;

            result[b]++;
            result[c]++;
        }
        else
        {
            result[number] ++;
        }

        return result;
    }
}




public class main {

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

        int[] result = new int[10];

        for(int i=1;i<=1000;i++)
        {
            int[] test = split.squeze(i);

            for(int y=0;y<10;y++) {
                result[y] += test[y];
            }
        }

        for(int i=0; i<10;i++)
        {
            System.out.println(i+ ":  "+ result[i]);
        }
    }

}




2020/07/14 11:09

허병우

a = [x for x in range(1,1001)]
b = {0:0,1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0}
for i in a:
    for j in str(i):
        b[int(j)] = b[int(j)]+1
b

2020/07/17 17:15

hand coder

비전공자라 그런지 정규식은 이용못하겠네요..

L=[str(i)[j] for i in range(1,1001) for j in range(len(str(i)))]
for p in [str(i)+":"+str(L.count(str(i))) for i in range(10)]:
    print(p)

2020/07/26 06:19

김병관

package Lv_1;

public class count_Number {
    int[] array = new int[10];

    public void make_count() {
        for(int i=1; i<=100; i++) {
            if(i==1000) {
                array[1]++;
                array[0]+=3;
            } else if(i>=100){
                array[i/100]++; //100의자리
                array[(i%100)/10]++; //10의 자리 => 100으로 나눈 나머지에서 10으로 나눔
                array[(i%100)%10]++; //1의 자리 => 위에서 10의 나머지만 구함
            } else if(i>=10) {
                array[i/10]++;
                array[i%10]++;
            } else {
                array[i]++;
            }
        }
    }

    public void print() {
        for(int i=0; i<array.length; i++) {
            System.out.print(i + ":" + array[i] + "개  ");
        }
    }
    public static void main(String args[]) {
        count_Number cn = new count_Number();
        cn.make_count();
        cn.print();
    }
}

2020/08/03 17:33

김승현

n=""
for i in range(1,1001,1):
    n += str(i)


print(n.count("0"))
print(n.count("1"))
print(n.count("2"))
print(n.count("3"))
print(n.count("4"))
print(n.count("5"))
print(n.count("6"))
print(n.count("7"))
print(n.count("8"))
print(n.count("9"))

코드 1개월차 코린이 입니다. 조언은 달게 받아드리겠습니다.

2020/09/04 19:09

gree Yu

public class test4 {
    public static void main(String[] args) {
        int[] input = {10, 11, 12, 13, 14, 15};
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

        for(int a = 0; a< 10; a++) {
            map.put(a,0);
        }

        for(int a : input) {
            String temp = String.valueOf(a);
            for(int i = 0; i < temp.length(); i++) {
                int x = Integer.parseInt(String.valueOf(temp.charAt(i)));
                map.replace(x, map.get(x)+1);
            }
        }

        for(int a = 0; a< 10; a++) {
            System.out.println(a+","+map.get(a));
        }
    }

해쉬맵을 이용한 풀이

2020/09/11 18:26

nazunamoe

#1~1000에서 각 숫자의 개수 구하기

list_1000 = []
char = ''
num_0 = 0
num_1 = 0
num_2 = 0
num_3 = 0
num_4 = 0
num_5 = 0
num_6 = 0
num_7 = 0
num_8 = 0
num_9 = 0


for i in range(1,1001):
    str1 = str(i)
    list_1000.append(str1)

for i in list_1000:
    char = char + i

for i in range(0,1000):
    if char[i] == '0':
        num_0 = num_0 + 1

    elif char[i] == '1':
        num_1 = num_1 + 1

    elif char[i] == '2':
        num_2 = num_2 + 1

    elif char[i] == '3':
        num_3 = num_3 + 1

    elif char[i] == '4':
        num_4 = num_4 + 1

    elif char[i] == '5':
        num_5 = num_5 + 1

    elif char[i] == '6':
        num_6 = num_6 + 1

    elif char[i] == '7':
        num_7 = num_7 + 1

    elif char[i] == '8':
        num_8 = num_8 + 1

    elif char[i] == '9':
        num_9 = num_9 + 1

print(num_0,num_1,num_2,num_3,num_4,num_5,num_6,num_7,num_8,num_9)

프로그래밍은 노가다라고 배웠습니다.

2020/09/18 13:16

이제동

nums = {'0':0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0}

def under_ten(num):
    nums[str(num)] += 1

def under_hundred(num):
    nums[str(num % 10)] += 1
    nums[str(int(num / 10))] += 1

def under_thousand(num):
    nums[str(num % 10)] += 1
    nums[str(int((num % 100) / 10))] += 1
    nums[str(int((num / 100)))] += 1

def each_nums_sum(data_list):
    for data in data_list:
        if data < 10:
            under_ten(data)
        elif data >= 10 and data < 100:
            under_hundred(data)
        elif data >= 100 and data < 1000:
            under_thousand(data)
        else:
            nums['1'] += 1
            nums['0'] += 3

if __name__ == "__main__":
    data_list = list(range(1,1001))
    each_nums_sum(data_list)

    for i in range(10):
        print("%d:%d개" % (i, nums[str(i)]), end=', ')

2020/09/29 09:41

이셩

public static void main(String[] args) {

        int[] number = new int[10];
        int n;
        for(int i = 1; i < 1001; i++) {                             
            n = i;
            number[n%10]++;
                while(n > 9) {
                    n /= 10;
                    number[n%10]++;
                }   
            }
        System.out.println(Arrays.toString(number));
        }

2020/09/30 01:48

B A

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

int main() {
    int numberArray[10];
    for (int i = 0; i < 10; i++) {
        numberArray[i] = 0;
    }
    for (int number = 1; number <= 1000; number++) {
        string stringNumber = to_string(number);

        for (int i = 0;i< stringNumber.length(); i++) {
            numberArray[stringNumber[i]-'0']++;
        }
    }

    for (int i = 0; i < 10; i++) {
        cout << i << ": " << numberArray[i] << endl;
    }

    return 0;

}

2020/10/01 19:03

김동현

def solve(a,b):
    num = [0]*10
    for i in range(a,b+1):
        x = str(i)
        for j in x:
            num[int(j)] += 1

    count=0
    for i in num:
        print("%d:%d개, "%(count,i),end='')
        count+=1

2020/10/01 20:54

jaewook Lee

a = []

for i in range(1,1001):
    i = str(i) 
    a.append(i)

a = ','.join(a) #list를 문자열로 변환

for k in range(0,10):
    k = str(k)
    b = a.count(k)
    print('{}의 갯수는 {}개 입니다.'.format(k, b))

2020/10/02 20:46

유태훈

n=[0,0,0,0,0,0]
for i in range(10,16):
    a,b=str(i)[0],str(i)[1]
    n[1]+=1
    n[int(b)]+=1
print('0:{0[0]}개, 1:{0[1]}개, 2:{0[2]}개, 3:{0[3]}개, 4:{0[4]}개, 5:{0[5]}개'.format(n))

2020/10/04 11:15

AppleFarmer

class RangeCounter:
    def __init__(self):
        pass
    def getNum(self,a,b):
        all = ""
        for num in range(a,b+1):
            all += str(num)
        print("0 :", all.count("0"))
        print("1 :", all.count("1"))
        print("2 :", all.count("2"))
        print("3 :", all.count("3"))
        print("4 :", all.count("4"))
        print("5 :", all.count("5"))
        print("6 :", all.count("6"))
        print("7 :", all.count("7"))
        print("8 :", all.count("8"))
        print("9 :", all.count("9"))


a = 10
b = 15

c = RangeCounter()
c.getNum(a,b)

2020/10/09 23:51

footsize

public class num_count {
    static int[] count = new int[10];

    public static void b(int num){
        for(int i =1;i<=num;i++) {
            int a = i;
            while(a!=0) {
                count[a%10]++;
                a/=10;
            }
        }

    }

    public static void main(String[] args) {

        b(1000);
        for(int i =0; i <10; i++) {
        System.out.print(count[i] + " ");
        }
    }

}

2020/10/13 10:49

ᆞᄉ

num = str(input("다섯개의 숫자를 입력하세요(쉼표를 사용하여 구분):"))

cnt_0 = num.count('0')
cnt_1 = num.count('1')
cnt_2 = num.count('2')
cnt_3 = num.count('3')
cnt_4 = num.count('4')
cnt_5 = num.count('5')
cnt_6 = num.count('6')
cnt_7 = num.count('7')
cnt_8 = num.count('8')
cnt_9 = num.count('9')


print('0:%d, 1:%d, 2:%d, 3:%d, 4:%d, 5:%d, 6:%d, 7:%d, 8:%d, 9:%d'  %(cnt_0,cnt_1,cnt_2,cnt_3,cnt_4,cnt_5,cnt_6,cnt_7,cnt_8,cnt_9))

2020/10/17 08:24

계진석

파이썬, collections 의 Counter 함수를 썼습니다. 11~15 까지 작은수로 해보고 1~1000까지 적용했습니다. 개수들이 정확한지는 잘 모르겠네요

from collections import Counter

str_num_list = list(map(str, range(1, 1001)))
cnt = Counter()
for num in str_num_list:
    cnt += Counter(num)

print(cnt)
for key, value in cnt.items():
    print(f'{key}: {value}')

2020/10/18 17:20

방금프로그래밍시작함

dic = dict.fromkeys([i for i in range(10)], 0)

for i in range(1, 1001):
    for j in range(10):
        if str(i).find(str(j)) != -1:
            dic[j] += str(i).count(str(j))

for keys, values in dic.items():
    print("{0}은 {1}개" .format(keys, values), end=" ")
    print()

# 0은 192개
# 1은 301개
# 2은 300개
# 3은 300개
# 4은 300개
# 5은 300개
# 6은 300개
# 7은 300개
# 8은 300개
# 9은 300개

2020/10/19 01:47

vcne0705

import numpy as np
counter = np.zeros(10)
for i in range(1,1001):
    for j in range(10):
        counter[j] += str(i).count(str(j))

for j in range(10):
    print("%d: %d" % (j, counter[j]))

2020/10/28 12:39

aryagaon

temp=[0,0,0,0,0,0,0,0,0,0] for num in range(1,1001): #0~1000 for tp in (str(num)): temp[int(tp)]+=1

for i in range(10): print(i,":",temp[i],"개")

2020/11/04 15:08

고태욱

count = []

for i in range(9):
    count.append(0)

for num in range(1,1001):
    for i in range(len(str(num))) :
        for k in range(9):
            if str(num)[i] == str(k) :
                count[k] = count[k] + 1

print(count)

2020/11/13 09:15

DSHIN

package codeDojang;


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

        int[] num = new int[10];


        for(int i=1;i<=1000;i++) {
            int tmp=i;
            while((tmp/10)!=0) {
            num[tmp%10]++;
            tmp/=10;
            }
            num[tmp]++;
        }

        for(int i=0;i<10;i++) {
            if(num[i]==0)continue;
            else System.out.println(i+" : "+num[i]);
        }


    }
}

2020/11/16 21:36

yijun kim

count = [0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    for k in range(0,10):
            count[k] += str(i).count(str(k))
for k in range(0,10):
    print(str(k)+":"+str(count[k])+"개")

2020/11/18 17:49

김우석

list1=list(map(int,input().split()))

list2=[]

for i in range(list1[0],list1[1]+1):
  str1=str(i)
  for k in range(len(str1)):
    list2.append(int(str1[k]))


for x in range(0,10):
  print(x,"의개수:",list2.count(x))

2020/11/18 22:15

장래희망파이썬마스터

num = {i:0 for i in range(10)}

for i in range(1,1001):
    for j in str(i):
        num[int(j)] += 1

print(num)

2020/11/23 03:53

안상원

k={'0':0,'1':0,'2':0,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0}

for i in range(1,1001,1):

  j=str(i)

  for z in j:

    if z in k:

      k[z]=k[z]+1

print(k)

2020/11/26 22:57

전준혁

파이썬이에요

print( {i : str(list(range(1,1001))).count(str(i)) for i in range(10)} ) # 딕셔너리 내포

# 결과 {0: 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300}

2020/11/28 02:55

코딩초딩

package main;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int num1 = sc.nextInt();
        String[] str = new String[num1-num];
        int[] arData = new int[10];
        for (int i = 0; i < str.length; i++) {
            str[i] = " " + num + i;
        }
        for (int i = 0; i < str.length; i++) {
            for (int j = 0; j < str[i].length(); j++) {
                for (int j2 = 0; j2 < 10; j2++) {
                    if ((int)str[i].charAt(j) == j2) {
                        arData[j2] += 1;
                    }                   
                }
            }
        }
        for (int i = 0; i < 10; i++) {
            System.out.println(i + ":" + arData[i]);
        }
    }
}

2020/12/09 01:13

김준혁


public class pro5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a = new int[10];
        for(int i=1; i<1001; i++) {
            a[i%10]++;
            if(i>=10)
                a[i/10%10]++;
            if(i>=100)
                a[i/100%10]++;
            if(i>=1000)
                a[i/1000%10]++;
        }
        for(int i=0; i<a.length; i++)
            System.out.println(i+"의 개수 : "+a[i]);

    }

}

2020/12/09 21:39

이정섭

a = []
for i in range(1, 1001):
    a += list(str(i))

for j in range(10):
    print("%s : " % j, a.count(str(j)))

파이썬으로 작성했습니다.

1부터 1000까지의 자연수를 쪼개어 리스트에 넣고 그 리스트에서 0부터 9까지의 숫자를 세어 출력하는 코드입니다.

2020/12/19 23:32

임준혁

list=[]
for i in range(1,1001): #리스트에 1부터 1000까지의 숫자를 넣고
    list.append(str(i)) #문자열로 변환시킨다

list_str='&'.join(list) #리스트에 담긴 1부터 1000까지 문자를 '&'로 이어붙인다

for i in range(1,10):
    print(i,"의 갯수는: ",list_str.count(str(i))) #이어 붙인 하나의 문자열에서 0부터 9까지 문자 갯수를 센다

2020/12/20 16:44

코딩팡팡

def count(start,end):
    import numpy as np
    data = np.array(list(str([x for x in range(start,end+1)])))
    num_count = ['{} : {}개'.format(num,sum(data==str(num))) for num in range(10)]
    for i in num_count:
        print(i)

2020/12/23 09:35

hankyu

dic = {}
for i in range(1, 1001):
    list = ','.join(str(i)).split(',')
    for j in list:
        if j in dic:
            dic[j] = dic[j] + 1
        else:
            dic[j] = 1

print(dic)

2021/01/04 16:26

코딩뚜

a = [0 for i in range(10)]
i = 1
while i <= 1000:
    temp = list(str(i))
    for j in temp:
        a[int(j)] += 1
    i += 1

2021/01/07 11:42

박성진

result = {}

for x in range(1,1001) :
    for a in str(x) :
        if a in list(result.keys()) :
            result[a] += 1
        else :
            result[a] = 1
print(result)

2021/01/09 22:20

­장태호 / 학생 / 원자핵공학과

dic={x:0 for x in range(0,10)}
for x in range(1,1001):
    for integer in str(x):
        dic[int(integer)]=dic[int(integer)]+1


print(dic)

2021/01/13 22:18

dong hoon

count={ x:0 for x in range(0,10) }

for x in range(1,1001):
    for i in str(x):
        count[int(i)]+=1

print(count)

2021/01/15 16:41

김지원

output = [0 for _ in range(10)]
for i in range(1, 1000+1):
    for j in range(0, 10):
        output[j] = int(output[j])+str(i).count(str(j))

for x in range(0, 10):
    print(f"{x}:{output[x]}", end=" ")

2021/01/16 14:08

asdfa

n = {x:0 for x in range(10)}
for i in range(1,1001):
    for j in str(i):
        n[int(j)]+=1
print(n)

2021/01/19 12:00

손우민

a = range(1,1001)
b = (str(list(a)))

total = {}
for i in range(0,10):
    C = b.count(str(i))
    total[i]=C

print(total)

딕셔너리 구조를 더 이해했으면 더 간단한 풀이가 나올 수 있었네요

2021/01/22 21:51

fox.j

start_num = int(input("시작 숫자 : "))
end_num = int(input("끝 숫자 : "))

list = []

for n in range(start_num, end_num+1):
    num_len = len(str(n))
    n = str(n)
    for i in range(num_len):
        list.append(n[i])


list = sorted(list)

for i in range(10):
    count = list.count(str(i))
    if count > 0:
        print(f"{i}의 개수 : {count} 개")

2021/01/24 14:38

Jino

let number=[0,0,0,0,0,0,0,0,0,0];

    for (let i = 1; i <=1000; i++) {
        i<10 ? number[i]++ :  splitNum(i);
    }
    let j=0;
    number.map((el)=>{console.log(''+j+':'+el+'개 '); j++;})

    function splitNum(i) {
        const str=String(i);
        const spNum=str.split('');
        const num=spNum.map((el)=>Number(el))

        num.map((el)=>number[el]++)
        number.map((el)=>{

        })
    }

2021/01/27 14:31

wldus

from collections import defaultdict

result = defaultdict(int)
for i in range(1, 1001):
    for j in str(i):
        result[j] += 1
print(result)

2021/01/31 17:28

Ha

#include <stdio.h>

int main()
{
    int start;
    int end;
    scanf("%d %d", &start, &end);
    int narr[10] = {0, };
    int mok;
    for(int i = start; i <= end; i++)
    {
        mok = i;
        while(mok != 0)
        {
            narr[mok % 10]++;
            mok /= 10;
        }
    }
    for(int i = 0; i < 10; i++)
    {
        if(narr[i] != 0)
        {
            printf("%d : %d개\n", i, narr[i]);        
        }

    }
}

c언어 입니다

2021/01/31 23:17

dae wan


ll = {x:0 for x in range(0,10)}

def CountNumber():
    N = int(input('Number : '))
    for i in range(1,N+1):
        temp = str(i)
        for j in range(10):
            for k in range(len(temp)):
                if int(j) == int(temp[k]):
                    ll[j] += 1

    print(ll)
if __name__ == '__main__':
    CountNumber()

2021/02/02 13:01

서해원

sum = ''
for i in range(1, 1001):
    sum += str(i)

for k in sorted(set(sum)):
    print(k,":",sum.count(k))

2021/02/05 21:54

개촙오

[파이썬]

# 숫자의 개수를 세는 변수 생성
for j in range(10):
    globals()["cnt{}".format(j)] = 0

# 숫자의 각 자릿수로 쪼개고 갯수를 더함
for i in range(1, 1001):
    if 0 < i < 10:
        for num in range(10):
            if i == num:
                globals()["cnt{}".format(num)] += 1

    if 10 <= i < 100:
        for num in range(10):
            if i//10 == num:
                globals()["cnt{}".format(num)] += 1
            if i%10 == num:
                globals()["cnt{}".format(num)] += 1

    if 100 <= i < 1000:
        for num in range(10):
            if i//100 == num:
                globals()["cnt{}".format(num)] += 1
            if (i % 100) // 10 == num:
                globals()["cnt{}".format(num)] += 1
            if (i % 100) % 10 == num:
                globals()["cnt{}".format(num)] += 1

    if i == 1000:
        cnt1 += 1
        cnt0 += 3

for num in range(10):
    print("%d: %d개" % (num, globals()["cnt{}".format(num)]))

2021/02/11 15:57

PenLoo

n = str(list(range(1, 1001)))

for i in range(10):
    print(f'{i} : {n.count(str(i))} 개')

2021/02/12 18:19

pathworker

def count_digit(num):
    digit = {}

    for num in range(1, num + 1):
        str_num = str(num)
        for i in str_num:
            if i not in digit:
                digit[i] = 1
            else:
                digit[i] += 1

    return digit

print(count_digit(1000))

2021/02/12 18:51

오세훈

numbers = []

for n in range(1, 1001):
    for s in str(n):
        numbers.append(s)

for i in range(10):
    print('{}: {}'.format(i, numbers.count(str(i))))

2021/02/18 16:41

원유준

l0=0
l1=0
l2=0
l3=0
l4=0
l5=0
l6=0
l7=0
l8=0
l9=0

for i in range(1,1001):
    a=str(i)
    for x in a:
        if x == '0':
            l0+=1
        elif x == '1':
            l1+=1
        elif x == '2':
            l2+=1
        elif x == '3':
            l3+=1
        elif x == '4':
            l4+=1
        elif x == '5':
            l5+=1
        elif x == '6':
            l6+=1
        elif x == '7':
            l7+=1
        elif x == '8':
            l8+=1
        elif x == '9':
            l9+=1

print('0:',l0,'1:',l1,'2:',l2,'3:',l3,'4:',l4,'5:',l5,'6:',l6,'7:',l7,'8:',l8,'9:',l9)

이렇게 긴 코드를...

dic={i:0 for i in range(0,10)}

for x in range(1,1001):
    for y in str(x):
        dic[int(y)]+=1

print(dic)

딕셔너리와 반복문만 잘 활용하면 이렇게 간결하게 표현이 가능하네요. 저는 아직 갈길이 먼 것 같습니다.

2021/02/25 10:58

최우진

dict_cnt = {}
for i in range(1, 1001):
    for j in str(i):
        if j in dict_cnt.keys():
            dict_cnt[j]+=1
        else:
            dict_cnt[j]=1

for k, v in dict_cnt.items():
    print(f'{k}: {v}개 ', end='')

2021/03/25 20:22

잘해보자

for i in range(10):
    print(i,":", str(list(range(1,1001))).count(str(i)), "개,", end='  ')

2021/04/06 11:47

윤태현

str_nums = str(list(range(1, 1001)))
result = {}
for i in range(10):
    result[i] = str_nums.count(str(i))
print(result)

[결과]

{0: 192, 1: 301, 2: 300, 3: 300, 4: 300, 5: 300, 6: 300, 7: 300, 8: 300, 9: 300}

<파이썬 3>

2021/04/06 22:18

Ruo Lee

from collections import Counter

rtn_list = []
for a in range(1, 1001):
    rtn_list += [int(n) for n in str(a)]
print(Counter(rtn_list))

2021/04/07 10:42

hezuk

Python입니다.

>>> def digit_counter(start, end):
...     counter = [0] * 10
...     for n in range(start, end):
...         for digit in str(n):
...             counter[int(digit)] += 1
...     return counter
...
>>> digit_counter(10, 16)
[1, 7, 1, 1, 1, 1, 0, 0, 0, 0]
>>> digit_counter(1, 1001)
[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

2021/04/11 15:19

최용

str1 = "".join(list(str(num) for num in range(1, 1001)))
for i in range(10):
    print("번호" + str(i) + "의 갯수는 : " + str(str1.count(str(i))))

2021/04/13 17:23

와장창

count={{x} : 0 for x in range(1,10)}

for i in range(1,1001):
    for j in str(i):
        count[int(j)] += 1
print(count)

2021/04/20 16:18

하이퍼

#메모리를 좀 많이 먹을거 같긴 한데.. collections.Counter 를 사용했습니다.

import collections

total=[]

def countNum(start,end):
    for i in range(int(start),int(end)+1):
        total.extend(list(str(i)))

    count_obj = collections.Counter(total)
    print("0:{} 1:{}".format(count_obj['0'],count_obj['1']))

2021/04/25 14:48

최태호

cnt_li = [int(num) for x in range(1,1001)
          for num in str(x)]
result = {}
for i in range(10):
    result[f'{i}'] = cnt_li.count(i)
print(result)

파이썬 3.9 // list comprehension 중첩과 f문자열 formatting 이용.

2021/04/28 01:54

illus

sum_lst = []
for i in range(1,1001):
    lst = [int(x) for x in str(i)]
    sum_lst += lst
# print(sum_T)

for j in range(10):
    cnt_j= sum_lst.count(j)
    print(f'{j}:', cnt_j,'개')

2021/04/28 15:22

bravesong

제가 초보라서 가장 초보 스럽게...

s = []
for i in range(1, 1001):
    for d in range(0,len(str(i))):
        letter = str(i)
        add = letter[d:d+1]
        s.append(add)
for j in range(0,10):
    print("{0}의 갯수 = {1}".format(str(j),s.count(str(j))))

2021/05/07 22:11

최정호

for x in range(10):
    print('%d: %d'%(x,''.join(map(str, range(1001))).count(str(x))))

데이터 타입을 유의해서 봐야해서 오래 걸린 문제였네요 ㅜㅠ

2021/05/09 15:22

ss2663

a=[0,0,0,0,0,0,0,0,0,0]

for i in range(1,1001):
    for j in range(0,10):
        k=str(i)
        if str(j) in k:
            a[j]+=k.count(str(j))

t=0
while t<1000:
    print("{0}의 개수 : {1}".format(t,a[t]))
    t+=1

이건 좀 짧게 쓴 것 같은데....!! 일단 올리고 풀이 보겠습니다

2021/05/11 00:50

Happy Day


n = 0
c = 0
l = []
while n < 1001 :    
    n1 = str(n)
    n += 1
    for i in n1:
        l.append(i)
while c <10 :
    c1 = l.count(f'{c}')
    print(c1)
    c += 1

2021/05/11 15:13

약사의혼자말

x = { x:0 for x in range(0,10) }
for y in range(1,1001):
  for i in str(y):
    x[int(i)] += 1

print(x)


3

2021/05/26 21:27

jaesik

a={0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
for i in range(1,1001) :
    i=str(i)
    k=list(i)
    for b in range(0,len(k)) :
        k[b]=int(k[b])
        a[k[b]]+=1

2021/05/27 22:44

김도군

python 3.9.5입니다.

num_list = [0]*10
for i in range(1, 1001):
    for j in str(i): num_list[int(j)] += 1
for k in range(10): print(str(k) + ': ' + str(num_list[k]))

실행 결과입니다.

0: 192
1: 301
2: 300
3: 300
4: 300
5: 300
6: 300
7: 300
8: 300
9: 300

2021/05/30 19:51

이준우

print({k:''.join(map(str, range(1,1001))).count(str(k)) for k in range(10)})

2021/06/21 13:48

김준우

ss2663님께 힌트를 받았습니다 - 김준우, 2021/06/21 13:55
sum_list=[]
for i in range(1,10):
    sum_list.append(0)

for j in range(1,1001):
    for i in str(j):
        sum_list[int(i)-1]+=1

2021/06/23 08:34

inkuk ju

num1000=list((range(1,1001)))
numCnt=[0 for i in range(10)]

for i in range(len(numCnt)):
     for j in range(len(num1000)):
        numCnt[i]+=str(num1000[j]).count(str(i))
print(numCnt)

2021/06/23 19:32

김민준

def count_num():
    start = int(input("시작 숫자 : "))
    final = int(input("마지막 숫자 : "))
    dic = {
        x : 0 for x in range(0, 10)
    }
    for i in range(start, final + 1):
        for j in str(i):
            dic[int(j)] += 1
    return dic
print(count_num())

2021/07/01 20:43

김준규

#codingdojing_countNum

numDic = {}

for i in range(10):         
    numDic.setdefault(str(i), 0) #dictionary initializtion

for num in range(1,1001):
    for c in str(num):
        numDic[c] += 1    #각 자리 추가


for i in numDic.items():
    print(i)

"""
('0', 192)
('1', 301)
('2', 300)
('3', 300)
('4', 300)
('5', 300)
('6', 300)
('7', 300)
('8', 300)
('9', 300)
"""

2021/07/09 11:39

Jaeman Lee

def number(min, max):
    lst = []
    for x in range(min, max + 1):
        lst = lst + list(str(x))  
    for y in range(0,10):
        print("{0}의 갯수는 {1}개 입니다.".format(str(y),(lst.count(str(y)))))

2021/07/11 14:31

billy han

list=[]
for i in range(1,1001):
    list.append(i)
for j in range(10):
    print("%d:"%j, str(list).count(str(j)), "개")  

2021/07/16 11:07

‍이성동[ 학부휴학 / 산업경영공학부 ]

zero_count = 0
one_count = 0
two_count = 0
three_count = 0
four_count = 0
five_count = 0
six_count = 0
seven_count = 0
eight_count = 0
nine_count = 0

for i in range(1, 1001):
    i = str(i)
    for j in i:
        if j == "0": zero_count += 1
        if j == "1": one_count += 1
        if j == "2": two_count += 1
        if j == "3": three_count += 1
        if j == "4": four_count += 1
        if j == "5": five_count += 1
        if j == "6": six_count += 1
        if j == "7": seven_count += 1
        if j == "8": eight_count += 1
        if j == "9": nine_count+= 1

print(f'''
    0:{zero_count}
    1:{one_count}
    2:{two_count}
    3:{three_count}
    4:{four_count}
    5:{five_count}
    6:{six_count}
    7:{seven_count}
    8:{eight_count}
    9:{nine_count}
''')



찐초보

2021/07/17 12:31

Annoymouse

python으로 작성되었습니다.

dic = {}
for i in range(10):
    key = str(i)
    dic[key] = 0

for number in range(10, 16):
    for n in str(number):
        dic[n] += 1

for i in range(10):
    key = str(i)
    if dic[key] != 0:
        print(key + ' : ' + str(dic[key]) + '개')

2021/07/23 17:49

baek choi

result =dict() n_list = range(1001) def func(n): return list(str(n)) for n in range(1, 1001) : for k in func(n) : if result.get(k) is None: result[k] = 1 else: result[k] +=1 print(result)

2021/07/28 01:56

Hyungwoo Lee

예전에 처음 시작했을때 그냥 쭉 썼어요...

o = 0
I = 0
II = 0
III = 0
IV = 0
V = 0
VI = 0
VII = 0
VIII = 0
IX = 0 
숫자_나열 = 0 
for i in range(1,1001):
   숫자_나열 = str(숫자_나열) + str(i) 

o = str(숫자_나열).count('0') 
I = str(숫자_나열).count('1')
II = str(숫자_나열).count('2')
III= str(숫자_나열).count('3')
IV = str(숫자_나열).count('4')
V = str(숫자_나열).count('5')
VI = str(숫자_나열).count('6')
VII = str(숫자_나열).count('7')
VIII = str(숫자_나열).count('8')
IX = str(숫자_나열).count('9') 

print('0 = %d, 1 = %d, 2 = %d, 3 = %d, 4 = %d, 5 = %d, 6 = %d, 7 = %d, 8 = %d, 9 = %d' %(o, I, II, III, IV, V, VI, VII, VIII, IX))

2021/08/08 23:20

Percy


num = ""
for t in range(1 ,1001):
    num += str(t)

for f in range(10):
    a = num.count('%d' % f)
    print("%d의 개수 : %d" % (f,a))

2021/08/10 15:17

서현준

java

package exam;

public class Ex02 {

    public static void main(String[] args) {

        // 0, 1, 2, 3, 4, 5, 6, 7, ,8, 9가 담길 그릇
        int [] index = new int [10];

        // 0~1000까지 
        for(int i = 0; i < 1001; i++) {
            // 1의 자리 수 각 인덱스마다 저장
            index[i%10]++;
            // 10의 자리 수 각 인덱스마다 저장
            if(i >= 10) {
                index[(i/10)%10]++;
            }
            // 100의 자리 수 각 인덱스마다 저장
            if(i >= 100) {
                index[(i/100)%10]++;
            }
            // 1000의 자리는 index[1]에 저장하면 된다
            if(i == 1000) {
                index[i/1000]++;
            }
        }
        for(int i =0; i<index.length; i++) {
            System.out.print(i + ": " + index[i] + (i == 9 ? "":", "));

        }
        // 결과
//      0: 193, 1: 301, 2: 300, 3: 300, 4: 300, 
//      5: 300, 6: 300, 7: 300, 8: 300, 9: 300
    }

}

2021/08/12 23:10

전채

list=[] # 리스트 사용
for generate in range(1,11):
    list.append(0)
for i in range(1,1001):
    for j in str(i):
        j=int(j)
        list[j]+=1
print(list)

2021/08/15 11:13

쥬쥬

countnum = 0
countzero = 0  
for i in range(1,1000):
   for j in str(i):
        if j =="1" :
           countnum += 1 #1~999 까지 각 숫자 개수 동일
        elif j == "0" : #0은 따로
            countzero += 1
print("0의갯수 = %d, 1의갯수 = %d, 2~9의 각 갯수 = %d" %(countzero + 3, countnum + 1, countnum)) 
#1000에서 1한개 0세개 더함

2021/08/22 17:50

//python

st = int(input("시작할 숫자를 입력하세요>"))
fn = int(input("마지막 숫자를 입력하세요>"))
a = ""
for i in range(st,fn+1):
    a += (str(i))
for c in range(10):
    c = str(c)
    print("{}:{}개".format(c,a.count(c)),end=" ")

2021/08/26 14:35

박대선

count = [0]*10

for x in range(1,1000):
    for i in str(x):
        count[int(i)] += 1

for idx, count in enumerate(count):
    print("{} : {}개".format(idx, count))

2021/08/26 16:01

코딩버거

A=[]
for i in range(1, 1001):
    A += list(str(i))

for i in range(10):
    print(A.count(str(i)), end=' ')

2021/09/04 12:58

trim39r

result=[0,0,0,0,0,0,0,0,0,0]
for num in range(1,1001):
    for i in str(num):
        result[int(i)]+=1
for j in range(10):
    print('{0}: {1}개'.format(j,result[j]),end=', ')

2021/09/17 16:03

ninanino

Number_Appear = [] Number_Checking = [] Number = 0 Number_over_10 = 0 Number_over_100 = 0

position = 0 for i in range(1,10) : Number_Appear.append(i) for i in range(1,10) : Number_Checking.append(0) for i in range(0,1000) : Number = Number + 1 if Number <10 : if Number in Number_Appear : Number_Checking[Number_Appear.index(Number)]=+1 elif 9 < Number < 100 : Number_over_10 =str(Number) for i1 in range(0,2) : if int(Number_over_10[i1]) in Number_Appear : Number_Checking[Number_Appear.index(int(Number_over_10[i1]))]= Number_Checking[Number_Appear.index(int(Number_over_10[i1]))] +1 elif Number > 99 : Number_over_100 =str(Number) for i1 in range(0,3) : if int(Number_over_100[i1]) in Number_Appear : Number_Checking[Number_Appear.index(int(Number_over_100[i1]))]= Number_Checking[Number_Appear.index(int(Number_over_100[i1]))] +1

2021/09/18 18:21

권숙철

numbers = [0 for i in range(10)] for i in range(1,1001): for j in str(i): numbers[int(j)] += 1 for i, j in enumerate(numbers): print(i, " : ", j)

2021/09/24 16:51

송효근

fn, sn = map(int, input('두개의 정수를 입력하세요: ').split())

nl = []
for l in range(fn, sn+1):
  nl += str(l)

for sn in sorted(set(nl)):
  c = 0
  for cn in nl:
    if sn == cn:
      c += 1
  print(f'{sn}:{c}개 ', end='')

2021/09/28 18:37

Charles

start = int("10")
end = int("15")
numbers = [0 for i in range(10)]

for i in range(start, end+1):
    i = str(i)
    for j in i:
        j = int(j)
        numbers[j] += 1

print(numbers)

2021/10/04 20:10

송효근

void main()
{   
    map<char, int> nummap;

    for (int i = 0; i <= 9; i++)
        nummap[i+ '0'] = 0;

    for (int i = 0; i <= 1000; i++)
    {
        char* temp = new char[5];
        sprintf(temp, "%d", i);
        for (int j = 0; j < strlen(temp); j++)
        {
            nummap[temp[j]]++;
        }
    }
}

2021/10/07 14:17

aozora18

0:192개 1:301개 2:300개 3:300개 4:300개 5:300개 6:300개 7:300개 8:300개 9:300개

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

        for(int i = 1; i<1001; i++) {
            for(int j = 0; j<(i+"").length(); j++) {
                count[(i+"").charAt(j)-48] += 1;
            }
        }
        for(int i=0; i< count.length; i++) {
            System.out.printf("%d:%d개 ", i, count[i]);
        }

    }

2021/10/24 09:41

박대현

num = 0
result = [0,0,0,0,0,0,0,0,0,0]

while (num<1000):
    num=num+1
    c=0
    b=list(map(int,list(str(num))))
    while (c<10):
     result[c]=result[c]+b.count(c)
     c=c+1

if num==1000:
   c=0
   while c<10:
     print(c,":",result[c])
     c=c+1

2021/11/04 22:55

Save Life

a = { i1:0 for i1 in range(0,10)}

for i1 in range(1,1001):
    for i2 in str(i1):
        a[int(i2)] += 1
print(a)

2021/11/26 16:58

이창현


b = [0 for _ in range(0,10)]

for i in range(1,1001)  :
    a = str(i)
    for k in range(0,10)   :
        b[k] += a.count(str(k))


print(b[9])

2021/12/15 23:28

양캠부부

n, m = map(int, input('From ~ To  ~ : ').split())
temp_list = [list(map(int, str(x))) for x in range(n, m + 1)]
whole_list = [y for x in temp_list for y in x]
count_list = [whole_list.count(x) for x in set(whole_list)]
result = dict(zip(set(whole_list), count_list))
print(result)

2021/12/31 15:20

bryn0726

temp = [0,0,0,0,0,0,0,0,0,0]

def countNum(i):
    for i in str(i):
        temp[int(i)]+=1

for i in range(10,16):
    countNum(i)

print(temp)

2022/01/07 14:47

BANG

s=[]
for i in range(1,1001):
    for n in str(i):
        s.append(n)

for m in range(10):
    print(m,':', s.count(str(m)))

2022/01/20 17:14

로만가

// Rust

use std::collections::HashMap; use std::string::ToString;

fn main() {

let (start, end) = (1, 1000);
let mut map: HashMap<char, u32> = HashMap::new();

// 정수를 문자열->character로 바꿔, 각 character를 HashMap의 key로 사용
// Entry를 이용해 &mut를 한 번에 얻음
for i in start..=end {
    for c in i.to_string().chars() {
        let count = map.entry(c).or_default();
        *count += 1;
    }
}

// HashMap key순서 대로 프린트
for i in 0..=9 {
    let j = std::char::from_digit(i, 10).unwrap();
    println!("{} : {}", j, map[&j]);
}

}

2022/01/25 23:54

JW KIM

count = [0,0,0,0,0,0,0,0,0,0]

for i in range (1,1001):
    for j in str(i):
        count[int(j)] += 1

for cnt in range(10):
    print(cnt,':',count[cnt],'개')

2022/01/28 17:15

엄태용

package org.javaturotials.ex;
import java.util.*;
import java.util.stream.Collectors;

public class test {
    public static void main(String[] args) {    
    int[] arr = new int[10];
    for(int i=1; i<=1000; i++) {
        if(i<10) {
            arr[i]++;
        }
        else {
            String a = String.valueOf(i);
            String[] arr2 = a.split("");
            for(int j=0; j<a.length(); j++) {
                int b = Integer.valueOf(arr2[j]);
                arr[b]++;
            }
        }
    }
    for(int i=0; i<10; i++) {
        System.out.println(i + ": " + arr[i] + "개");
    }
    }
    }

2022/02/21 00:18

Kkubuck

b=input('0~9중 한 가지 숫자를 입력하세요:')
a=str(list(range(1,1001)))
print(a.count(b))

2022/02/23 18:28

mintou

i = 0
sum=0
list_n=[0,0,0,0,0,0,0,0,0,0]
while i<=999:
    i+=1
    for n in range(0, len(str(i))):
        a=str(i)[n]
        list_n[int(a)]+=1

print(list_n)

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

2022/03/01 18:25

코딩초보박영규

using System;
using System.Collections.Generic;

namespace FirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            int one = 0; int two = 0; int three = 0; int four = 0; int five = 0; int six = 0;int seven = 0; int eight = 0; int nine = 0; int zero = 0;

            for(int i=1; i<1001; i++)
            {
                string n = Convert.ToString(i);
                for(int j = 0; j<n.Length; j++)
                {
                    char m = n[j];
                    if (m == '1')
                        one += 1;
                    else if (m == '2')
                        two += 1;
                    else if (m == '3')
                        three += 1;
                    else if (m == '4')
                        four += 1;
                    else if (m == '5')
                        five += 1;
                    else if (m == '6')
                        six += 1;
                    else if (m == '7')
                        seven += 1;
                    else if (m == '8')
                        eight += 1;
                    else if (m == '9')
                        nine += 1;
                    else if (m == '0')
                        zero += 1;
                }
            }
            Console.WriteLine("0 : " +  zero);
            Console.WriteLine("1 : " + one);
            Console.WriteLine("2 : " + two);
            Console.WriteLine("3 : " + three);
            Console.WriteLine("4 : " + four);
            Console.WriteLine("5 : " + five);
            Console.WriteLine("6 : " + six);
            Console.WriteLine("7 : " + seven);
            Console.WriteLine("8 : " + eight);
            Console.WriteLine("9 : " + nine);
        }
    }
}

C#

2022/03/11 20:19

rah_9

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

        for (int i = 1; i < 10001; i++)
            {
            String str = Integer.toString(i);

            for (int j = 0; j < str.length(); j++)
                {
                char ch = str.charAt(j);

                if (ch == '8')
                    {
                    count += 1;
                    }
                }
            }

        System.out.println(count);
        }

2022/03/25 11:52

김상재

a = 0 b = 0 c = 0 d = 0 e = 0 f = 0 g = 0 h = 0 k = 0 l = 0

for i in range(10, 16): for j in str(i): if int(j) == 0: a += 1 if int(j) == 1: b += 1 if int(j) == 2: c += 1 if int(j) == 3: d += 1 if int(j) == 4: e += 1 if int(j) == 5: f += 1 if int(j) == 6: g += 1 if int(j) == 7: h += 1 if int(j) == 8: k += 1 if int(j) == 9: l += 1

print(a, b, c, d, e, f, g, h, k, l)

2022/04/11 14:13

yunjae

x={1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,0:0} print(x) for i in range(1000): for k in str(i): for j in x: k=int(k) if k==j: x[j]+=1 print(x)

2022/04/11 15:47

yunjae

a=range(1,1001)
a=''.join(map(str,a))
for i in range(10):
    print('{}:{}개'.format(i, a.count(str(i))))

2022/04/13 11:05

이병휘

li = [".".join(str(i)).split('.') for i in range(1,1001)]
b = []
dic = {}
for i in range(len(li)):
    for j in li[i]:
        b.append(j)
for j in range(len(set(b))):
    dic[j] = b.count('%s' % j)
for k in range(len(dic)):
    print('{}: {}개'.format(k, dic[k]),end=', ')

2022/04/19 00:31

고구마츄

package com.algorithm.algorithmpractice.dojang;

import java.util.Arrays;

public class To1000 {
    public static void main(String[] args) {
        int[] arrForCount = new int[10];

        for(int i = 1; i <= 1000; i++){
            String number = Integer.toString(i);
            String[] temp = number.split("");
            for(int j = 0; j < temp.length; j++){
                int tempInt = Integer.valueOf(temp[j]);
                arrForCount[tempInt] += 1;
            }
        }

        System.out.println(Arrays.toString(arrForCount));
    }

}

재귀로 푸려다 실패하고 그냥 이중 반복문 돌렸습니다. 코로나 걸리면 멍청해 지는 듯

2022/05/01 17:15

inkuk ju

x = 0
a = []
while x < 1000:
  x += 1
  a.append(str(x))
b = [0,0,0,0,0,0,0,0,0,0]
for c in range(10):
  for i in range(1000):
    b[c] += a[i].count(f'{c}')
print(b)

2022/05/03 14:38

Jack Maker


import java.util.*;

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

        //10에서 15까지 각 자리를 차지하는 '숫자'의 개수를 구하기(카운팅)
        //10, 11, 12, 13, 14, 15이므로
        //'0'은 1개, '1'은 7개, '2'는 1개, '3'은 1개, '4'는 1개, '5'는 1개

        //반복적으로 각 자리수를 구해서 배열에 저장하기
        int[] numbers = new int[12]; //배열의 크기는 내가 직접 세어서 지정함...

        for(int i=10; i<=15; i++) {
            int index = i-10;
            numbers[index] = i%10; //1의 자리 숫자(10으로 나누었을 때의 나머지)
        }

        for(int i=10; i<=15; i++) { 
            int index = i-4;
            numbers[index] = i/10; //10의 자리 숫자(10으로 나누었을 때의 몫)
        }

        //배열의 출력 
        System.out.println(Arrays.toString(numbers));

        //카운팅하기(빈도수 구하기)
        HashMap map = new HashMap();

        for(int i=0; i<numbers.length; i++) { //배열에 담긴 숫자를 하나씩 읽어서 HashMap에 키로 저장
            if(map.containsKey(numbers[i])) {
                int value = (int)map.get(numbers[i]); 
                map.put(numbers[i], value + 1); //빈도수를 세기 위해서, 기존에 있던 키는 기존 값에 1을 더해서 저장 
            } else {
                map.put(numbers[i], 1); //기존에 없던 키는 값을 1로 저장
            }
        }

        //HashMap의 요소 출력하기(빈도수 출력)
        Iterator it = map.entrySet().iterator();

        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();     
            int value = (int)entry.getValue();
            System.out.println(entry.getKey() + "은 " + value + "개");
        }



    }
}

2022/05/09 16:08

코숏

자바로 풀어봤습니다. 시작점과 종점을 입력하시면 시작점과 종점까지의 각 숫자의 갯수를 반환합니다.

import java.util.Scanner;
import java.util.ArrayList;
import java.util.HashMap;

public class TestMain {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        ArrayList<Integer> numbers = new ArrayList<>();
        HashMap<Integer, Integer> counts = new HashMap<>();
        int start, end, i, number, storage;

        // 시작점과 종점 입력
        while(true) {
            System.out.println("시작점(자연수)을 알려주새요.:");
            start = scan.nextInt();

            System.out.println("종점(자연수)을 알려주세요.:");
            end = scan.nextInt();

            if(start<0||end<0||start>end) {
                System.out.println("잘못 입력하셨습니다.\n");
            }else {
                break;
            }
        }

        // 리스트 확인
        for(i = start; i<=end; i++) {
            numbers.add(i);
        }

        // 카운트
        for(i=0; i<numbers.size();i++) {
            number = numbers.get(i);

            while(number>0) {
                storage = number%10;

                if(counts.containsKey(storage) == false) {
                    counts.put(storage, 1);
                }else {
                    counts.put(storage, counts.get(storage)+1);
                }

                number /= 10;
            }

        }

        // 결과 출력
        System.out.printf(String.format("\n%d ~ %d까지의 각 숫자의 갯수는 다음과 같습니다.\n",start,end)+counts);
    }
}

2022/06/07 15:04

유로

num_list = [ ','.join(str(i)).split(',') for i in range(1,1001) ]
num_sum =sum(num_list, [])
for i in range(0,10):
    print(i,'의개수 : ',num_sum.count(str(i)))

파이썬입니당

2022/06/19 14:12

Hote


zero = 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
seven = 0
eight = 0
nine = 0

for i in range(1, 1001):
    number = str(i)
    zc = number.count("0")
    zero += zc

    oc = number.count("1")
    one += oc

    tc = number.count("2")
    two += tc

    thc = number.count("3")
    three += thc

    fc = number.count("4")
    four += fc

    fic = number.count("5")
    five += fic

    sc = number.count("6")
    six += sc

    sec = number.count("7")
    seven += sec

    ec = number.count("8")
    eight += ec

    nc = number.count("9")
    nine += nc

print(f"0은 {zero}개 1은 {one}개 2는 {two}개 3은 {three}개 4는 {four}개 5는 {five}개 6은 {six}개 7은 {seven}개 8은 {eight}개 9는 {nine}개 입니다")

완전 어렵게 풀었네요

2022/06/19 18:53

박종훈

참고하기 좋은 풀이들이 많네요

d = { x:0 for x in range(10) }

for i in range(1, 1001):
    ncomn = ','.join(str(i))
    for j in range(0, 10):
        d[j] += ncomn.count(str(j))

# print(d)

dk = list(d.keys())
dv = list(d.values())
for k in range(10):
    if dv[k] == 0: continue
    print("%d:%d개" % (dk[k], dv[k]), end=' ')

파이썬 3.8.5

2022/07/10 02:54

Estelle L

num_list = [ list(x) for x in input("Enter numbers: ").split(',')]

num_all = []

for i in range(len(num_list)):
    num_all += num_list[i]

for j in range(0,10):
    if str(j) in num_all:
        print("number of %d: %s" % (j, num_all.count(str(j))))

코딩 초보입니다.

많은 조언 부탁드립니다.

2022/07/12 17:16

WONCHEOL LEE

y = "".join([str(x) for x in range(1,1001)])
for i in range(10):
    print(i, y.count(str(i)))

2022/07/25 14:16

JC YUN

a=[]
b=0
for n in range(1,1001):
    while n > 0 :
        b = n % 10
        n //= 10
        a.append(b)
print([f'{i}의 개수:{a.count(i)}' for i in range(10)])

저는 숫자로 접근해서 풀었는데, 다른 분들 코드를 보니 문자로 접근하셨네요! 숫자로 생각한 경우, 입력된 숫자의 일의 자리를 계속 리스트에 추가하여 각 자리수를 반환하도록 하였습니다.

문자로 접근한 경우는 한번에 각 자리수를 세면 되는 더 편리한 것 같네요 배워갑니다~

2022/07/26 13:17

김보라

def counting_num(min, max):
    counting=[0]*10
    for i in range(min, max+1):
        for j in str(i):
            counting[int(j)]+=1

    print("{0} ~ {1} 까지의 각 숫자의 개수는 ".format(min, max), end="")
    state = False
    for i in range(10):
        if counting[i] != 0:
            if state == False:
                state = True
            else:
                print(",  ", end="")
            print("{0} : {1}개".format(i, counting[i]), end="")

counting_num(10, 15)

2022/07/27 18:00

김준성

#include<stdio.h>
int main(void)
{
    int count[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    char num[5];
    for (int i = 0; i < 1001; i++)
    {
        sprintf(num, "%d", i);
        int j = 0;
        while (num[j] != '\0')
        {   
            count[(int)num[j] - 48]++;  // 아스키코드 이용
            j++;
        }

    }

    for (int i = 0; i < 10; i++) printf("%d의 개수는 %d개입니다.\n", i, count[i]);
}

2022/07/31 00:53

코딩재미

python

number_1 = int(input("Start number : "))
number_2 = int(input("End number : "))
number = ''.join(map(str, range(number_1, number_2 + 1)))
for i in range(10) :
    print("%d : %d" % (i, number.count(str(i))))

2022/08/01 16:11

정재화

python

n1 = 1
n2 = 1000

numbers = [x for x in range(n1,n2+1)]
count = [0]*(10)

for x in numbers:
    for i in range(10):
        count[i] += str(x).count(str(i))

for x in range(10):
    print('{0}: {1}개'.format(x, count[x]))

2022/08/10 11:04

세라


num_digit = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(1,1001):
    for k in range(0,len(str(i))):
        num_digit[int(str(i)[k])] += 1

for i in range(0,10):
   print(num_digit[i])

2022/08/20 20:14

황정현

package ex;

public class Ex01 {
    public static void main(String[] args) {
        int zero = 0; int one = 0; int two = 0;
        int three = 0; int four = 0; int five = 0;
        int six = 0; int seven = 0; int eight = 0; int nine = 0;
        for (int i = 1; i <= 1000; i++) {
            String check = i + "";
            for (int j = 0; j < check.length(); j++) {
                if (check.toString().charAt(j) == '1') {
                    one++;
                } else if (check.toString().charAt(j) == '2') {
                    two++;
                } else if (check.toString().charAt(j) == '3') {
                    three++;
                } else if (check.toString().charAt(j) == '4') {
                    four++;
                } else if (check.toString().charAt(j) == '5') {
                    five++;
                } else if (check.toString().charAt(j) == '6') {
                    six++;
                } else if (check.toString().charAt(j) == '7') {
                    seven++;
                } else if (check.toString().charAt(j) == '8') {
                    eight++;
                } else if (check.toString().charAt(j) == '9') {
                    nine++;
                } else if (check.toString().charAt(j) == '0') {
                    zero++;
                }
            }
        }
        System.out.println("0의 개수 : " + zero);
        System.out.println("1의 개수 : " + one);
        System.out.println("2의 개수 : " + two);
        System.out.println("3의 개수 : " + three);
        System.out.println("4의 개수 : " + four);
        System.out.println("5의 개수 : " + five);
        System.out.println("6의 개수 : " + six);
        System.out.println("7의 개수 : " + seven);
        System.out.println("8의 개수 : " + eight);
        System.out.println("9의 개수 : " + nine);
    }
}

2022/08/30 22:22

Jay Choi



a = ""

for x in range (1,1001):
    a = a + str(x)

[a.count(str(i)) for i in range(0,10)]

이렇게 했습니다..

2022/09/02 13:38

정일산

입력받은 수를 split한후 -> 해당 숫자만큼 배열자리수를 count ++ 했습니다.

Scanner sc2 = new Scanner(System.in);
System.out.println("각 자리 수 개숫를 구하기 위한 숫자 시작과 끝을 입력하시오");
int startNum = sc2.nextInt();
int endNum = sc2.nextInt();

int[] numCnt = new int[10];

for(int i2=startNum; i2<=endNum; i2++) {
    String[] val = String.valueOf(i2).split("");
    int valLength = val.length;

    for(int i3 = 0; i3 < valLength; i3++) {
        int num = Integer.parseInt(val[i3]);
        numCnt[num]++;
    }

}
System.out.println("각 자리 숫자합은 다음과 같다" + Arrays.toString(numCnt));

2022/09/08 15:47

서영재

counts = {}

for i in range(0,1000):
    strarr = str(i+1)

    for j in strarr:
        if j in counts:
            counts[j] += 1
        else:
            counts[j] = 1

print(counts)

2022/09/16 23:33

이나영

tcl/tk 로 장석해보았습니다.

코드를 더 줄일수 있을까요 ?

#! /usr/bin/tclsh

for {set i 1} { $i <= 9} {incr i} { set num($i) 0}
for {set i 1000} { $i > 0 } {incr i -1} {
   for {set u [expr [string length $i] - 1 ]} {$u >= 0} {incr u -1} {
      set t [string index $i $u]
      incr num($t)
   }
}
foreach t [array names num] { puts "$t  == $num($t)"}

2022/10/11 16:15

조상우

파이썬입니다.

def each(n):
    N = str(n)
    G = []
    for k in range(0,10):
        G.append(N.count('%d' % k))
    return G

HAP = [0,0,0,0,0,0,0,0,0,0]
for i in range(1,1001):
    for j in range(0,10):
        HAP[j] += each(i)[j]

print(HAP)

한 숫자에 대해서 뽑는 함수 만들고 1~1000까지 리스트의 인덱스 별로 다 더해서 구해봤습니다. 출력 값 : [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

2022/10/28 13:50

이웅기


# 1~1000에서 각 숫자의 개수 구하기

list=[]

for x in range(1,1001):
    if len((str(x))) == 1:
        list.append(str(x))
    elif len((str(x))) == 2:
        list.append(str(x)[0])
        list.append(str(x)[1])
    elif len((str(x))) == 3:
        list.append(str(x)[0])
        list.append(str(x)[1])
        list.append(str(x)[2])
    else:
        list.append(str(x)[0])
        list.append(str(x)[1])
        list.append(str(x)[2])
        list.append(str(x)[3])

print("1의 개수 :", list.count("1"))
print("2의 개수 :", list.count("2"))
print("3의 개수 :", list.count("3"))
print("4의 개수 :", list.count("4"))
print("5의 개수 :", list.count("5"))
print("6의 개수 :", list.count("6"))
print("7의 개수 :", list.count("7"))
print("8의 개수 :", list.count("8"))
print("9의 개수 :", list.count("9"))
print("0의 개수 :", list.count("0"))

2022/11/09 18:16

­류예린

파이썬 입니다.

c[]

for m in range(0,10):

for i range(1,1001):

a+=str(i).count(str(m))

c+=[a]

a=0

print(c)

[192,301,300,300,300,300,300,300,300,300]

2022/12/01 17:34

조랭이떡

a,b = map(int, input().split())
l = []

for i in range(a,b+1):
    l = l + list(str(i))

for i in range(10):
    print("{}:{}개".format(i, l.count(str(i))), end =' ')

2022/12/20 12:31

박대선

// 다시 한 번 풀어보기... 어렵다..

import java.util.Arrays;

public class Q2__CountTo1000 {

    public static void main(String[] args) {
        int box[] = new int[10] ;
        for (int i = 1; i<= 1000 ; i++ ) {
            box[i % 10]++  ;  // 일의 자리별 박스 만들기 : i=3,13...993 => box[3] =  box[3] + 1 
            if ( i>=10 ) box [ (i/10)%10 ]++ ;      // 십의 자리 i=10,11,12..110,111...918,919 =>  box[1] = i/10%10
            if ( i>=100 ) box [ (i/100)%10 ]++ ;    // 백의 자리 i=500,501...599 =>  box[5] =  i/100%10(?)
            if ( i==1000 ) box [ 1 ]++ ;    // 천의 자리 i=1000  =>  box[1] ++
        }
        System.out.println(Arrays.toString(box));
    }
}

2023/01/29 17:44

Hyun

result=[0]*10
for i in range(1,1001):
    x=str(i)
    for j in x:
        result[int(j)]+=1
print(result)

2023/02/19 12:15

신찬희

HashMap<String,Integer> number = new HashMap<>();
for(int i = 1; i <= 1000; i++){
  String[] strs = i split by "";
  for(String str : strs){
    if(number.containsKey()){
      number.put(str,1);
    }else{
      number.put(str,number.get(str)+1);
    }
  }

}  
for(String str : number.keySet()){
    System.out.println(str + " " + number.get(str)+"개");
}
``````{.java}
HashMap<String,Integer> number = new HashMap<>();
for(int i = 1; i <= 1000; i++){
  String[] strs = i split by "";
  for(String str : strs){
    if(number.containsKey()){
      number.put(str,1);
    }else{
      number.put(str,number.get(str)+1);
    }
  }

}  
for(String str : number.keySet()){
    System.out.println(str + " " + number.get(str)+"개");
}

2023/02/26 11:31

권동하

for i in range(1,10): print(str(list(range(1,1001))).count('%d'%i))

2023/03/08 22:30

정길

intInput1 = [int(v) for v in input('정수 두 개 입력').split()]

counts=[0]*10
for i in range(intInput1[0],intInput1[1]+1):
    j=str(i)
    for k in range(len(j)):
        for x in range (10):
            if j[k]==str(x): counts[x]+=1

for i in range (len(counts)):
    print(i,':',counts[i])

2023/03/10 15:35

Sol Song

count=[0]*10

for x in range(1,1001):
    for i in str(x):
        count[int(i)]+=1

print(count)

2023/03/20 13:42

최준하

for idx in range(9):    
    a = str(list(range(1, 1001))).count(str(idx))
    print("{}의 갯수는 {}개입니다.".format(idx, a))

2023/04/15 23:02

이준수

for n in range(0,10):

  a=0

  for i in range(1,1001):

       b=list(str(i))

       a=a+ b.count(str(n))

print(a)

파이썬 3일차 입문자

또 풀었따! 시간 가는줄 모르고 풀게되네 ㅋㅋ

2023/04/27 17:03

한세록

class Program { static void Main(string[] args) { int[] arr = new int[10];

        for (int i = 1; i < 1001  ; i++)
        {
            string s = i.ToString();
            foreach (char c in s)
            {
                int index = c - '0';   
                arr[index] += 1;
            }
        }

        for (int i = 0; i < arr.Length; i++)
            WriteLine($"{i}의 사용 횟수는 {arr[i]}번.");
    }
}```{.cs}

```

2023/07/09 20:20

김나은

List comprehension, dictionary data 형식, list.count() 함수 이용

start, last = 1, 1000
nums_list = [int(a) for x in range(start, last + 1) for a in str(x)]
nums_list.sort()

cnt = {}
for i in nums_list:
    cnt[i] = nums_list.count(i)

print(cnt)

2023/07/23 17:49

Dongyoon Kim

num = [0] * 10

for i in range(1,1001):
   for j in str(i):
      spt = int(j)
      num[spt] += 1
for k in range(len(num)):
   print(k,":",num[k])

2023/08/10 18:11

siu yoon

from collections import Counter
import operator

nums = []
for num in range(10,16):
    nums.extend(list(str(num)))

result = [(a,b) for a, b in Counter(nums).items()]
result.sort(key=operator.itemgetter(0))
print(result)

2023/08/12 20:35

이광진

data = range(1, 1001)

real_list = []

for i in data:
    a = list(str(i))
    real_list.extend(a)


range = range(0,10)

for ii in range:
    print(real_list.count(str(ii)))

2023/08/30 14:38

jaemirong

cnt = {x:0 for x in range(0, 10)}
for num in range(1, 1001):
    while num > 0:
        cnt[num%10] += 1
        num //= 10
print(cnt)

2023/11/06 15:20

insperChoi

numbers = str(list(range(1, 1001)))
dic = {}
for i in range(10):
    dic[i] = numbers.count(str(i))
print(dic)

2024/02/03 15:09

리리

num=range(1,1001)
num = list(num)
for i in range(0,10):
    print(i,":",str(num).count(str(i)) , "개")

2024/02/21 16:01

버거킹

for i in range(10):
  nums = 0
  for x in range(1,1001):
    nums += str(x).count(str(i))
  print(f"{i} : {nums}개")

2024/04/23 01:06

czarmagnate

from collections import Counter

count = Counter(digit for x in range(1, 1001) for digit in str(x))
print(count)

2024/04/23 13:43

Briston

package solution.codingDojang;

public class Solution504 {

    public static void main(String[] args) {
        // 1~1000에서 각 숫자의 개수 구하기
//      예로 10 ~ 15 까지의 각 숫자의 개수를 구해보자
//
//      10 = 1, 0
//      11 = 1, 1
//      12 = 1, 2
//      13 = 1, 3
//      14 = 1, 4
//      15 = 1, 5
//
//      그러므로 이 경우의 답은 0:1개, 1:7개, 2:1개, 3:1개, 4:1개, 5:1개
        int start = 1; // 시작값
        int end = 1000; // 끝값
        // 0~9 숫자마다의 개수를 담을 배열 선언
        int[] arrTimes = new int[10]; // 초기값 0이 세팅됨.
        for (int i = start; i <= end; i++) {
            for (String e : String.valueOf(i).split("")) {
                // 문자 '0'에서 문자 '0'을 빼면 숫자 0이 된다.
                int current = (int) (e.charAt(0) - '0');
                arrTimes[current]++;
//              System.out.println(current + ": " + arrTimes[current]);
            }
        }
        for (int i = 0; i < arrTimes.length; i++) {
            System.out.println(i + ":" + arrTimes[i]);
        }

    }

}

[console]

0:192
1:301
2:300
3:300
4:300
5:300
6:300
7:300
8:300
9:300

2024/07/07 21:14

이준상

방법1.

from collections import Counter
cnt = Counter()
_ = [ cnt.update(x) for i in range(1, 1001) for x in str(i)]
print('결과:', cnt)
> 결과: Counter({'1': 301, '2': 300, '3': 300, '4': 300, '5': 300, '6': 300, '7': 300, '8': 300, '9': 300, '0': 192})

방법2.

def count(r, x): r[x] += 1
cnt = {str(i):0 for i in range(10)}
_ = [ count(cnt, s) for i in range(1, 1001) for s in str(i)]
print('결과:', cnt)
> 결과: {'0': 192, '1': 301, '2': 300, '3': 300, '4': 300, '5': 300, '6': 300, '7': 300, '8': 300, '9': 300}

2024/10/10 06:41

무므뭇

count = [0,0,0,0,0,0,0,0,0,0]
for n in range(1,1001):
    for i in range(len(str(n))):
        for j in range(10) :
            if str(j) == str(n)[i] :
                count[j] += 1
for a in range(10):
    print(f"{a}:{count[a]}번")

2024/12/12 07:16

Orange

from collections import Counter

a = int(input("원하는 숫자1:"))
b = int(input("원하는 숫자2:"))

num = Counter([n for i in list(map(str,range(a,b+1))) for n in i])

for n in sorted(num):
    print(f"{n}의 갯수:{num[n]}")

2025/12/25 18:42

k

for i in range(10):
    count = sum(str(x).count(str(i)) for x in range(1, 1001))
    print(f"{i}:{count}")

2026/05/04 21:28

우영재

목록으로