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)
from collections import defaultdict
d = defaultdict(int)
for n in range(1, 1001):
for x in str(n):
d[x] += 1
print(d)
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],"개")
파이썬 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
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");
}
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]
정답은 이렇습니다. 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] +"개, " );
}
}
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));
//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(", "));
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;
}
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))
#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]);
}
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입니다
# 한글 처리 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])
#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();
}
결과: {'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) # 결과 출력
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
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)))
for i in range(0, 10):
print("{} : {}개".format(i, str(list(range(1, 1001))).count(str(i))))
1부터 1000까지 쭉 나열하는 string만들어서 0부터 9까지 i가 반복하며 count하는 방식으로 풀었습니다.
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))))
뉴비가 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)))
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} )
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}
풀이 쓰는 거 들여쓰기도 안 되고 어케 하는지 하나도 모르겠다 존나 빡치네 구제좀
파이썬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())))
자바로 풀어봄
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] + " " );
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));
파이썬으로 작성했습니다. (파이썬 초보자입니다.)
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])
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주일 쫌 넘어가네요 (이게 첫 언어에요) 다음부터는 튜플이라도 쓸게요
>>> 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})
@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]++;
}
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)
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;
}
}
#파이썬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.')
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에 대한 값은 따로 했습니다.
파이썬 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)])
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;
파이썬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])
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
from collections import defaultdict
d = defaultdict(int)
for i in ''.join([str(i) for i in range(10, 16)]):
d[i] += 1
print d
파이썬 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))))
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까지 문자를 카운터 하는 방법으로 풀었습니다.
숫자가 커지면 메모리를 많이 쓰는 좋지않은 코드죠. 다른 분들의 소스를 보면서 많이 배워갑니다.
감사합니다.
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;
}
}
}
#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], "개 입니다.")
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();
}
}
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;
}
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])
}
}
파이썬 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
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)
}
}
# 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 개
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이 출렵됩니다
답은 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] );
}
}
# 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'),))
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]);}
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] )
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개
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=' ')
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);
}
}
자바로 생성자를 이용하여 계산했습니다.
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])
자바 컬렉션을 사용하여 풀어봤습니다 ㅠㅠ
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));
}
}
}
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]))
#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]);
}
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]);
}
}
}
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]);
}
}
}
#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;
}
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'))
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]);
}
}
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+", ");
}
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)]
재귀로 각 자리수를 구해서 배열에 넣고 올렸습니다.
#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);
}
}
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]);
}
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;
}
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')
지금까지 배운 거로 최대한 쥐어 짜내서 풀어봤습니다 ㅠㅠ 맞는 방법인지는 모르겠네요.. 정말 초보자라 한 이틀 고민했습니다..
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
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시간씩이나 고민했네요;; 아직 갈길이 머나 봅니다..
이제 막 코딩시작한 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");
}
}
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)
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]))
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();
}
}
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.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;
}
머리로 풀기
우선 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))))
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] //결과 출력
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)
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
그나저나 코딩을 오랜만에 해봐서 코드가 쓸데없이 기네요 ㅋㅋ
#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
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
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
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))
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]);
}
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)
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;
}
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번
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 사이의 수를 다시 입력하세요");
}
}
}
}
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]))
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)]
/**
*
*/
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]);
}
}
}
자바
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] + "개");
}
}
}
#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]);
}
}
}
#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]);
}
}
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=' ')
#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;
}
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
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] 이런 식으로 출력됩니다.
#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이라는 함수를 만들었습니다. 숫자 카운트는 정수를 문자열로 바꿔서 수행하였습니다.
#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
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;
}
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개
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))))
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] + " 개");
}
}
}
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], "개")
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)
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);
}
}
#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
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] + " ");
}
}
}
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
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
#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]);
}
}
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))
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]+"개");
}
}
}
안녕하세요. 뉴비입니다. 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
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
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)
#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;
}
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))
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);
}
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));
}
}
#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++로 작성했습니다.
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));
}
}
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]);
}
}
}
#!/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'
/* 자바로 작성했습니다. */
-- 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)));
}
}
}
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]);
}
}
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)
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)))
파이썬 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)
{str(x):str(list(range(1, 1001))).count(str(x)) for x in range(0,10)}
Python 2.7.12, Python 3.5.2에서 확인했습니다.
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]
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)
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]))
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]); } }
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();
}
}
}
눕눕이가 작성해본 파이썬입니다.
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)), "개")
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);
}
}
}
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
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')
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}
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]);
}
}
}
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]))
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);
}
}
}
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);
}
}
}
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))
/*
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]);
}
}
#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;
}
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);
}
}
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]);
}
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] + "개");
}
}
}
#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;
}
}
//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);
}
자바로 풀었습니다. 문제의 조건에서 입력된 값에 포함된 숫자(예를 들면 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);
}
}
}
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
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]+"개");
}
}
}
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]);
}
}
}
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]))
$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";
}
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])
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] + "개");
}
}
}
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);
}
}
// 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;
}
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);
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;
}
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]}");
}
#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]);
}
}
from collections import defaultdict
d = defaultdict(int) for n in range(1, 1001): for x in str(n): d[x] += 1
print(d)
#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]);
}
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]);
}
}
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
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();
}
}
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]))
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])
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]))
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
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])
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)
#-*- 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+"개")
처음으로 파이썬 배우고 풀어본건데 다른분들에 비해 너무 비교되네요 ^^; 다른분들에게 많이 배워가야겠습니다.
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);
}
}
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]) + "개")
/*
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;
}
}
import collections
counter = []
for i in range(1, 1001):
counter += list(str(i))
print collections.Counter(counter)
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)))
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
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)
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);
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
#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개 결과는 이렇게 나오네요
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)))
초급자 수준의 정석...
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)))
#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
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));
}
}
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까지의 숫자의 갯수를 나타내게 됩니다.
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);
}
}
}
#입력받는 부분
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 = ' ')
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 )
#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;
}
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개
from collections import defaultdict
d = defaultdict(int)
for n in range(1, 1001):
for x in str(n):
d[x] += 1
print(d)
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
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;
}
from collections import defaultdict
d = defaultdict(int) for n in range(1, 1001): for x in str(n): d[x] += 1
print(d)
from collections import defaultdict
d = defaultdict(int)
for n in range(1, 1001):
for x in str(n):
d[x] += 1
print(d)
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();
}
}
box = []
for a in range(1,1001):
box += list(str(a))
print({x : box.count(str(x)) for x in range(0,10)})
파이썬으로 작성했어요 제가 올린 사람중에서 코드가 젤 기네요 ㅋㅋㅋㅋ
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)
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]+"개");
}
}
노가다로 풀었긴 하지만 효율적인 코드는 아닌거 같습니다...
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;
}
}
파이썬입니다. 숫자입력 받게 했습니다
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'))
#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]);
}
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);
}
}
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], "개")
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)
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])")
}
from collections import *
d=defaultdict(int)
for x in range(1,1001):
for n in str(x):
d[x]+=1
print(d)
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] + "개 " );
}
}
}
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부터 입력받은수까지입니다. 아직 함수정렬은 배우지못해..
/*
* 예로 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
#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))
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
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)
#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를 활용 해서 카운팅 했어요~
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]
//c로 풀었음
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;
}
/*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]);
다른 답안들을 많이 봤는데 대부분 최대 값이 제한되있더라구요.(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개인 경우 표시되지 않습니다.");
}
}
#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;
}
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] + " 이다");
}
}
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))
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;
}
}
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;
}
}
//자바로 풀어 보았습니다.
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;
}
}
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+"개 ");
}
}
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)
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
코딩 초보라서 어렵내요
#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;
}
#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)
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)
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'),"입니다")
파이썬.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]) + ".")
for i in range(10):
a = str([j for j in range(10, 16)]).count(str(i))
print(r'{} => {}개'.format(i, a))
#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)
(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]);
}
#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]);
}
}
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)
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
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))
#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]);
}
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}
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] + "개");
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] + " 개 있습니다.");
}
}
}
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)
두 가지의 풀이입니다.
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;
}
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);
}
}
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);
}
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;
}
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))
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]);
}
}
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;
}
}
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));
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]+" 개");
}
}
}
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()
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문 돌리면 되려 속도가 엄청 느려지던데 이유 아시는분?
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(", "));
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}
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]);
}
}
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]);
자바....
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)))
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)
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개씩 나옵니다.
#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;
}
}
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
``````{.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()
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
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]+"개");
}
}
}
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] + "개 입니다.");
}
}
}
#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");
}
#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까지 훑으며 각각의 수를 카운트 업.
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)
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")
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]);
}
}
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)
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
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)
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],"입니다")
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");
}
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());
}
파이썬 초보자 입니다.
x = [0 for x in range(10)]
for i in range(1,1001):
for j in str(i):
x[int(j)] += 1
print(x)
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]);
}
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]);
}
}
}
파이썬의 사전(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)
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개
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)
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] + "개");
}
}
// 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)
}
}
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]))
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]);
}
}
}
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)
}
# 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
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개
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]);
}
}
}
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)
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 개
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 까지 세고 수동으로;;
초보입니다..;
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))
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))
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))))
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)
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)
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)
# -*- coding: utf-8 -*-
a = str(range(1,1001))
for i in range(10):
print "{}:{}개".format(i, a.count(str(i))),
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)개")
}
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;
}
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]);
}
}
(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)
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)))
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)
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)
for i in range(10):
nums=0
for j in range(1, 1001):
nums+=str(j).count(str(i))
else:
print('{}: {}개'.format(i, nums))
파이썬 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 개
s = ""
for i in range(1000):
s += str(i+1)
for i in range(10):
print("{} : ".format(str(i)),s.count("{}".format(i)),"개")
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))
파이썬 입니다.
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))))
자바에요... 허허....
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;
}
}
listx = []
for x in range(1001):
listx += str(x)
for y in range(10):
print(str(y) + ' : ' + str(listx.count(str(y))) + '개')
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개
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))
#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;
}
s=''
for x in range(1,1001):s+=str(x)
for i in range(10):print(str(i)+':%d'%s.count(str(i)), end=' ')
#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]);
}
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);
}
#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]);
}
}
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
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)+"개")
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입니다.
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
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가 변경되는 줄 모르고 코드를 이렇게 짰네요...
#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;
}
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)
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] + "개 입니다.");
}
}
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
값을 하나하나 다 비교할려해서 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)))
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],"개")
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))
python 입니다.
text = ''
for n in range(1001): text = text + str(n)
for c in range(10): print(str(c), text.count(str(c)))
파이썬
result = []
for i in range(1, 1000):
result += str(i)
for i in range(0, 10):
print("{}의 개수: {}".format(i, result.count(str(i))))
#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;
}
}
옮기며 배우는 중입니다
// 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]}");
}
범위를 정하여 값 구하기
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]);
}
}
}
}
(10 to 15).map(_.toString).flatten.groupBy(v => v).mapValues(_.size).foreach(println)
// 자바
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]);
}
}
// 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");
}
}
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))
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)
}
}
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;
}
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;
}
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)
파이썬 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)
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개
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]);
}
}
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()
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=", ")
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))))
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]))
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개 ```
파이썬 입니다.
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)
#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입니다
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}
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개
파이썬. 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]))
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 ]
num = int(input())
count = [0] * 10
for i in range(1,num+1):
for j in str(i):
count[int(j)] += 1
print(count)
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))
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)
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]);
}
}
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)))
#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}
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]))
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))
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
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)
#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,
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))
초보에염 히히
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
파이썬 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}')
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)
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))
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
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]);
}
}
[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]
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)
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]);
}
}
}
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],'개')
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),"개")
for i in range(0,10):
cnt = 0
for num in range(1,1001):
cnt+=str(num).count(str(i))
print('{}의 갯수는 {}개 입니다.'.format(i,cnt))
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)
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);
});
}
}
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] + " ");
}
}
}
digitDic = {}
for digit in range(10, 16):
for s in str(digit):
digitDic[s] = digitDic.get(s, 0) + 1
print(digitDic)
# 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)
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()
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)
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);
}
}
}
}
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
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],'개')
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);
}
}
자바로 풀었습니다~ 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]);
}
}
}
# -*- 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]))
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)))
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()
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
}
파이썬 입니다.
정답: [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)
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]))
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)
각 자리를 문자열 리스트로 변환 후 .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}
[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}
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}
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;
} ```
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# 기준으로 작성했습니다.
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]);
}
}
}
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.
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}
import collections
empty = ""
box = collections.Counter()
for i in range(1,1001):
a = str(i)
empty += a
box.update(empty)
print(box)
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=", ")
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));
}
}
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);
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))]++
}
}
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))
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
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)
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)))
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]))
accumul=str()
for i in range(1,1001):accumul+=str(i)
for j in range(10):print('%d:%d'%(j,accumul.count(str(j))))
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)
#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로 풀어봤습니다
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)
파이썬 3.7.2버전 입니다.
k = str(list(range(1, 1001)))
for t in range(0,10):
print(f'{t} are {k.count(str(t))}','/',end='')
#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;
}
}
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)
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 = " ")
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]))
Input = [x for x in range(1, 1001)]
for i in range(10):
print('{0}: {1}'.format(i, str(Input).count(str(i))))
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}개')
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)
선형시간으로 끝내는 솔루션은 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;
}
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;
}
파이썬 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])+"개")
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()))
#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;
}
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])
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)
list_tot = []
for i in range(1,101): for j in list(str(i)): list_tot.append(j)
for k in range(0,10): k = str(k) tot = list_tot.count(k) # print(tot) print("%s의 갯수 : %s " % (k, tot))
파이썬 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)),'개')
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~
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]) + "개")
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))
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)
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++;
}
}
}
}
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)
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)
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)
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
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)
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))
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=' ')
파이썬 초보입니다.. 그냥 올려본거에요
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))
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);
}
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])))
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)
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)
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))
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))
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)
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]
answer = {}
for i in range(1, 1001):
for key in str(i):
answer.setdefault(key, 0)
answer[key] += 1
print(answer)
파이썬3입니다.
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
count = [0] * 10
for i in range(1, 1001):
for j in str(i):
count[int(j)] = count[int(j)] + 1
print(count)
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
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));
for i in range(0,10):
count = 0
print(i,' : ',str(list(x for x in range(1,1001))).count(str(i)),'개',end = ', ' )
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)))
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])
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)))
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 + "개 있습니다.");
}
}
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
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를 리스트에 넣었더니 리스트안에 리스트로 만들어져서 리스트안의 요소를 하나씩 거내어 리스트로 넣기위해서 입니다.
파이썬으로 작성했습니다.
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)
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));
*/
}
}
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 }
파이썬 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))
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]))
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]
파이썬입니다. 고수분들이 정말 많네요. 배워갑니다.
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)
파이썬으로 작성했습니다. 입력값을 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'))
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;
}
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)
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)))
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)))
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))))
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}")}')
파이썬 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=', ')
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)
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)
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)
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'))
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=' ')
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)
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]);
}
}
}
#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))
파이썬 3.7 딕셔너리를 이용하면 더 좋아겠네요
data = [0] * 10
for d in range(1, 1001):
for i, v in enumerate(str(d)):
data[int(v)] += 1
print(data)
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))
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])
#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']
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)),"개")
#갯수 카운트
#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);
}
파이썬 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]
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
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)
'''
파이썬 입니다.
'''
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)
파이썬 노가다 버전과 정리한 버전입니다.
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')
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);
}
}
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)
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=' ')
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)
파이썬입니다.
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)}개")
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까지 받아서 하나하나 쪼개서 구했습니다.
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)])
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
배열을 사용하지 않고 풀어보려했으나 쉽지않네요
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]);
}
}
}
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)))
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("")
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주 되었는데, 실력이 늘었으면 해서 안 보고 열심히 해봤습니다!
먼저 숫자를 리스트화 한다음에 문자열로 바꿔서 다시 리스트로 만들었구요. 그리고나서 리스트의 카운터 기능을 이용해서 세어봤습니다.
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)
{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}
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]);
}
}
}
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
비전공자라 그런지 정규식은 이용못하겠네요..
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)
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();
}
}
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개월차 코린이 입니다. 조언은 달게 받아드리겠습니다.
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));
}
}
해쉬맵을 이용한 풀이
#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)
프로그래밍은 노가다라고 배웠습니다.
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=', ')
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));
}
#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;
}
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
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))
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))
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)
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] + " ");
}
}
}
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))
파이썬, 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}')
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개
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]))
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],"개")
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)
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]);
}
}
}
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])+"개")
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))
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)
파이썬이에요
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}
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]);
}
}
}
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]);
}
}
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까지의 숫자를 세어 출력하는 코드입니다.
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까지 문자 갯수를 센다
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)
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)
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
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)
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)
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)
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=" ")
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)
딕셔너리 구조를 더 이해했으면 더 간단한 풀이가 나올 수 있었네요
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} 개")
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)=>{
})
}
from collections import defaultdict
result = defaultdict(int)
for i in range(1, 1001):
for j in str(i):
result[j] += 1
print(result)
#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언어 입니다
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()
sum = ''
for i in range(1, 1001):
sum += str(i)
for k in sorted(set(sum)):
print(k,":",sum.count(k))
[파이썬]
# 숫자의 개수를 세는 변수 생성
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)]))
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))
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))))
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)
딕셔너리와 반복문만 잘 활용하면 이렇게 간결하게 표현이 가능하네요. 저는 아직 갈길이 먼 것 같습니다.
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='')
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>
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))
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]
str1 = "".join(list(str(num) for num in range(1, 1001)))
for i in range(10):
print("번호" + str(i) + "의 갯수는 : " + str(str1.count(str(i))))
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)
#메모리를 좀 많이 먹을거 같긴 한데.. 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']))
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 이용.
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,'개')
제가 초보라서 가장 초보 스럽게...
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))))
for x in range(10):
print('%d: %d'%(x,''.join(map(str, range(1001))).count(str(x))))
데이터 타입을 유의해서 봐야해서 오래 걸린 문제였네요 ㅜㅠ
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
이건 좀 짧게 쓴 것 같은데....!! 일단 올리고 풀이 보겠습니다
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
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
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
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
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)
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())
#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)
"""
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)))))
list=[]
for i in range(1,1001):
list.append(i)
for j in range(10):
print("%d:"%j, str(list).count(str(j)), "개")
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}
''')
찐초보
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]) + '개')
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)
예전에 처음 시작했을때 그냥 쭉 썼어요...
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))
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))
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
}
}
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)
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세개 더함
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=" ")
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))
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=', ')
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
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)
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='')
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)
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]]++;
}
}
}
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]);
}
}
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
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)
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])
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)
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)
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)))
// 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]);
}
}
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],'개')
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] + "개");
}
}
}
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]
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#
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);
}
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)
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)
a=range(1,1001)
a=''.join(map(str,a))
for i in range(10):
print('{}:{}개'.format(i, a.count(str(i))))
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=', ')
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));
}
}
재귀로 푸려다 실패하고 그냥 이중 반복문 돌렸습니다. 코로나 걸리면 멍청해 지는 듯
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)
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 + "개");
}
}
}
자바로 풀어봤습니다. 시작점과 종점을 입력하시면 시작점과 종점까지의 각 숫자의 갯수를 반환합니다.
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);
}
}
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)))
파이썬입니당
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}개 입니다")
완전 어렵게 풀었네요
참고하기 좋은 풀이들이 많네요
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
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))))
코딩 초보입니다.
많은 조언 부탁드립니다.
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)])
저는 숫자로 접근해서 풀었는데, 다른 분들 코드를 보니 문자로 접근하셨네요! 숫자로 생각한 경우, 입력된 숫자의 일의 자리를 계속 리스트에 추가하여 각 자리수를 반환하도록 하였습니다.
문자로 접근한 경우는 한번에 각 자리수를 세면 되는 더 편리한 것 같네요 배워갑니다~
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)
#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]);
}
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))))
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]))
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])
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);
}
}
입력받은 수를 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));
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)
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)"}
파이썬입니다.
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]
# 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"))
파이썬 입니다.
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]
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 =' ')
// 다시 한 번 풀어보기... 어렵다..
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));
}
}
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)+"개");
}
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])
for idx in range(9):
a = str(list(range(1, 1001))).count(str(idx))
print("{}의 갯수는 {}개입니다.".format(idx, a))
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일차 입문자
또 풀었따! 시간 가는줄 모르고 풀게되네 ㅋㅋ
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}
```
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)
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])
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)
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)))
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)
numbers = str(list(range(1, 1001)))
dic = {}
for i in range(10):
dic[i] = numbers.count(str(i))
print(dic)
for i in range(10):
nums = 0
for x in range(1,1001):
nums += str(x).count(str(i))
print(f"{i} : {nums}개")
from collections import Counter
count = Counter(digit for x in range(1, 1001) for digit in str(x))
print(count)
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
방법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}
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]}번")