0부터 9999까지 8을 포함하지 않는 수는 총 몇개일까?
8, 108, 888, 9998 등은 8을 포함하고 있는 수입니다. 111, 299, 4 등과 같은 수는 8을 포함하지 않는 수 입니다.
60개의 풀이가 있습니다.
alist = []
cc = 0
for ii in range(10000):
c = 0
for i in str(ii):
if i == '8':
c = 1
if c == 0:
cc += 1
print(cc)
count = 0
for i in range(0, 10000):
a = list(str(i))
if "8" not in a:
count += 1
print(count)
파이썬으로 풀이해보았습니다.
def res(s_num):
re = 0
for i in range(s_num+1):
if '8' not in str(i):
re += 1
return re
print(res(10000))
lst = []
z =1
while z <= 1000:
print(z)
if "8" in str(z):
lst.append(z)
else:
pass
z += 1
print(lst)
print(len(lst))
while문으로 화려하게 작성해보았습니다.
#include <stdio.h>
#include <math.h>
// 숫자를 찾는 함수 입니다.
int count_number(int input_number, int start_n, int end_n)
{
// 8을 찾는 총 count입니다.
int number_find_count = 0;
// start_n + end_n의 개수입니다. 0부터 9999이니 총 10000 입니다.
int total_count = end_n - start_n + 1;
int result_count = 0;
// 찾는 숫자는 1~9로 fix했습니다.
if((input_number < 1 ) || (input_number > 10))
{
printf("Find Number range is from 1 to 9 \r\n");
return -1;
}
// 0~9999의 숫자를 찾습니다.
for(int i = start_n; i< end_n; i++)
{
for(int j = 0; j< 4; j++)
{
// pow라는 함수는 10지수승입니다. 10의 0은 1이고 10의 1승은 10, 2승은 100입니다.
// 10, 100, 1000, 10000으로 나누면서 8이 발견하면 count를 증가하고 loop를 빠져나갑니다.
int mod_value = pow(10, (j+1));
int remainder = input_number * pow(10,j);
if((i%mod_value)==(remainder))
{
number_find_count++;
printf("find value (%d) % (%d) == %(%d) \r\n", i , mod_value, remainder);
break;
}
}
}
printf("A total %d of number(%d) from %d to %d were detected.\r\n", number_find_count ,input_number, start_n, end_n);
// 8을 찾은 결과에서 숫자 전체 개수를 빼면 의도한 결과가 나옵니다.
result_count = total_count - number_find_count;
printf("There are %d numbers excluding %d. \r\n", result_count, input_number);
return 0;
}
int main(int argc, char *argv[])
{
count_number(8, 0, 9999);
return 0;
}
a = list(range(-1,10000))
c=10000
for i in range(len(a)):
b = list(str(i))
if str(8) in b:
c-=1
print(c)
Java는 없어서 이렇게 풀어봤습니다. 개선점이 있다면 답글 부탁드립니다.
public class NumberAlgorithm {
private static final int MAX_NUM = 9999;
public static void main(String[] args) {
int resultMinus = 0;
int i = 0;
for (; i <= MAX_NUM; i++) { // 9999까지 Loop
// break시작지점
char[] digit = String.valueOf(i).toCharArray();
for (int j = 0; j < digit.length; j++) { // digit의 자리수 Loop
if (digit[j] == '8') { // 8이 포함된 자리가 있다면 Minus 카운트 후 break
resultMinus++;
break;
}
}
}
System.out.println("[0~9999] 8을 포함하지 않는 결과 ::: " + (i - resultMinus)); // 0부터 9999까지의 숫자 개수 - 8포함된 숫자 개수
}
}
# 숫자 세기 알고리즘
def foo():
count = 0
target = "8"
for i in range(0, 10000):
if target not in str(i):
count += 1
return count
print(foo())
cnt = 0
for i in range(0, 10000):
s = f"{i}"
if s.find('8') == -1:
print(s)
cnt += 1
print()
print("cnt: ", cnt)
# Codingdojang 274
total_list=[int(i) for i in range(0,10000)]
Exclude_eight=[int(i) for i in total_list if '8' not in str(i)]
print(len(Exclude_eight))
count = 1
for i in range(1,10000) : while i > 0 : if i % 10 != 8 : i = int(i/10) elif i % 10 == 8 : count += 1 break
print(10000-count)
Python 3.10
def main():
rst = len([i for i in range(10_000) if '8' not in str(i)])
print(rst)
if __name__ == "__main__":
main()
Python. 'not in'이면 간단하게 해결할 것을 괜히 복잡하게 생각해서 정규식까지 가져왔네요;;
import re
p=re.compile('8')
numbers=list(range(0,10000))
count=0
for number in numbers:
if p.search(str(number)):
pass
else:
count += 1
print(count)
result = 0
check = 0
for i in range(0,10000):
k=str(i)
check = 0
for j in k:
if int(j) == 8:
if check ==0:
result= result-1
check = 1
result+=1
print(result)
total = 0
for i in range(0,10000):
if '8' in str(i):
continue
total+=1
print("0부터 9999까지 8을 포함하지 않는 수의 갯수 => "+str(total))
숫자를 문자열로 취급해 8을 포함하는지 검사하는 방식이 아니라 숫자 형태로 검사하는 방식입니다. 일의 자리에 8이 있는지 검사하고 완료되면 일의 자리를 제거하고 그 다음(십의 자리를 검사했으면 백의 자리) 자리를 검사하는 방식입니다.
void _Test2()
{
string result = "";
for (int i = 0; i < 10000; ++i)
{
int n1 = i % 10;
if (n1 == 8)
{
result += i + ", ";
continue;
}
int n2 = i / 10;
n2 = n2 % 10;
if (n2 == 8)
{
result += i + ", ";
continue;
}
int n3 = i / 100;
n3 = n3 % 10;
if (n3 == 8)
{
result += i + ", ";
continue;
}
int n4 = i / 1000;
//n4 = n4 % 10;
if (n4 == 8)
{
result += i + ", ";
continue;
}
//if (s.Contains("8") == true)
// result += s + ", ";
}
Debug.Log(result);
}
count = 0
for i in range(10000) :
for j in str(i) :
if j == '8' :
count += 1
break
else :
pass
print(10000 - count)
package project1.project;
import java.util.ArrayList;
class calculate {
int usedata;
int appearancenumber;
ArrayList<Integer> datalist = new ArrayList<Integer>();
public calculate(int data) {
this.usedata = data;
}
public void cal() {
for (int n=0; n<usedata; n++) {
String q = String.valueOf(n);
ArrayList<String> s = new ArrayList<>();
for (int r = 0; r<q.length(); r++) {
char aaa = q.charAt(r);
String aa = String.valueOf(aaa);
s.add(aa);
}
if (s.contains("8")) {
int mmm;
} else {
datalist.add(n);
}
}
}
public ArrayList<Integer> returndata() {
return datalist;
}
}
public class project {
public static void main(String[] arg) {
calculate c = new calculate(10000);
c.cal();
ArrayList<Integer> result = c.returndata();
System.out.println(result.size());
}
}
java로 풀었습니다
0부터 세어야 하기 때문에 return에서 'end값에 1을 더한 값'에서 8이 포함된 개수를 빼야 합니다. 매개변수로는 (9999, 8)을 주었고 결과는 6561이 나왔습니다.
public static long count(int end, int target) {
return (end + 1) - IntStream.rangeClosed(0, end).filter(v -> (v + "").contains("" + target)).count();
// return (end + 1) - (int) IntStream.rangeClosed(0, end).filter(v -> String.valueOf(v).contains(String.valueOf(target))).count();
}
int main() {
int sum = 10000;
for(int i=0;i<10000;i++){
int temp = i;
if(8000<=i && i<9000) sum -=1;
else{
i %= 1000;
if(800<= i && i<900) sum -=1;
else{
i %= 100;
if(80<=i && i<90) sum -= 1;
else{
i %= 10;
if (i==8) sum -= 1;
}
}
}
i=temp;
}
printf("%d\n",sum);
return 0;
}
class FindNumber:
def __init__(self,maxNum,findNum):
self.maxNum = maxNum
self.findNum = findNum
def searchNum(self):
list = []
print("최대숫자:" ,self.maxNum , "찾을 수:", self.findNum)
for x in range(0, self.maxNum):
tempValue= str(x)
if tempValue.find(str(self.findNum)) >=0 :
list.append(x)
# print(f"{tempValue} is contained {self.findNum}")
return list
fn= FindNumber(1000,8)
list = fn.searchNum()
print(list)
경우의 수 문제이므로 코딩없이 간단히 풀 수 있습니다..^^ 총 4자리의 숫자이고, 각 자리에 0, 1, 2, 3, 4, 5, 6, 7, 9의 9개의 숫자 중 하나가 올 수 있으므로 9x9x9x9를 계산하면 6561로 답을 구할 수 있습니다.
# 0-9999 중 8을 포함하지 않은 수 세기
noteight = 0
for i in range(10000):
if "8" not in str(i):
noteight += 1
print(noteight)
print('0부터 9999까지 8을 포함하지 않는 수는 :')
cnt = 0
for i in range(0, 10000):
if '8' not in str(i):
cnt += 1
print(cnt) # 6561
print('각 자리에 올 수 있는 수는 9 가지 : ',9**4) # 6561
num = 0
for i in range(0,9999):
if i % 1 == 8:
num += 1
elif i % 10 == 8:
num += 1
elif i % 100 == 8:
num += 1
elif i % 1000 == 8:
num += 1
print(10000-num)
count = 0
for i in range(10000):
str_i = str(i)
for num in str_i:
if '8' in str_i:
count+=1
break
print(10000-count)
print(len(set(a for a in range(0,10000) if a//1000 != 8 and a%1000//100 != 8 and a%100//10 != 8 and a%10 != 8)))
' 엑셀VBA
Sub TEST()
Dim i As Long
Dim cnt As Long
cnt = 0
For i = 0 To 9999
If InStr(Format(i, "0000"), "8") = 0 Then
cnt = cnt + 1
End If
Next
MsgBox (cnt)
End Sub
기존 파이썬 string기초만 이용하면
def do_not_provide_8_number(input_n):
"""
input_n이 숫자고 그때 input_str이 8을 포함하는지 하지 않는지 판단한다.
8을 포함하면 true를, 포함하지 않으면 false를 리턴한다.
"""
flag = False
input_str = str(input_n)
for i in range(len(input_str)):
if input_str[i]=="8":
flag = True
return flag
count=0
for j in range(9999):
flag = do_not_provide_8_number(j)
count+=flag
print(count)
num = 0 count = 0
for num in range(0,10000): num_str = str(num) if '8' in num_str: num += 1 continue else: num += 1 count += 1
print(count)
# 1개의 8이 있을 경우: 예) XXX8(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 1개 할당하는 경우의 수는 조합으로 구함: C(4, 1) = 4!/1!(4-1)! = 4
# 경우의 수 x 9 x 9 x 9: 4 x 9 x 9 x 9 = 2,916
# 2개의 8이 있을 경우: 예) XX88(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 2개 할당하는 경우의 수는 조합으로 구함: C(4, 2) = 4!/2!(4-2)! = 6
# 경우의 수 x 9 x 9: 6 x 9 x 9 = 483
# 3개의 8이 있을 경우: 예) X888(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 3개 할당하는 경우의 수는 조합으로 구함: C(4, 3) = 4!/3!(4-3)! = 4
# 경우의 수 x 9: 4 x 9 = 36
# 4개의 8이 있을 경우: 예) 8888(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 4개 할당하는 경우의 수는 조합으로 구함: C(4, 4) = 4!/4!(4-4)! = 1
# 경우의 수 x 1: 1 x 1 = 1
# 0 ~ 9999: 총 10,000개 중에 8이 1개 이상 있는 경우는 2,916 + 483 + 36 + 1 = 3,439
# 0 ~ 9999: 총 10,000개 중에 8이 포함되지 않는 경우는 10,000 - 3,439 = 6561
import math
total = 0
for n in range(1, 5): # n: 8의 개수, 8이 없는 자리수: 4 - n
cnt = math.comb(4, n)
sum = cnt * 9**(4-n)
total += sum
print("total = ", total)
print("total_without_8 = ", 10000 - total)