879개의 풀이가 있습니다.
음....
10,000 에는 8 이 없으니 무시하고, 1 부터 9999 까지
X X X 8 인 경우 : 1,000개 ( X X X 는 세자리이므로 0 0 0 ~ 9 9 9 까지 천개)
X X 8 X 인 경우 : 1,000개 ( X X X 는 세자리이므로 0 0 0 ~ 9 9 9 까지 천개)
X 8 X X 인 경우 : 1,000개 ( X X X 는 세자리이므로 0 0 0 ~ 9 9 9 까지 천개)
8 X X X 인 경우 ; 1,000개 ( X X X 는 세자리이므로 0 0 0 ~ 9 9 9 까지 천개)
총 4,000 개 아닌가?
파이썬 2.7 입니다.
print str(range(1,10001)).count('8')
JAVA
public class CountingEight {
public static void main(String[] args) {
for (int i=0; i<=10000; i++){
searchEight(i);
}
System.out.println("1에서 10,000 사이에 존재하는 8의 개수는? "+count);
}
private static int count = 0;
public static void searchEight(int num){
if (num%10==8) count++;
if (num>10) searchEight(num/10);
}
}
1에서 10,000 사이에 존재하는 8의 개수는? 4000
파이썬은 한줄로 가능하군요!!! @_@ 제 능력으로는 이렇게 밖에.... 하아~~
int count = 0;
for(int i = 1; i < 10001; i++)
{
for(int j = i; j > 0; j /= 10)
{
if(j % 10 == 8)
{
count++;
}
}
}
int main()
{
int i,j,n,m;
int sum;
sum = 0;
for (i=0; i<10; i++){
for(j=0; j<10; j++){
for (n=0; n<10; n++){
for(m=0; m<10; m++){
if( m == 8 ){sum = sum+1;}
if( n == 8){sum = sum+1;}
if ( j == 8){sum = sum+1;}
if( i == 8 ){sum = sum+1;}
}
}
}
}
printf("1~10000까지 8을 가진 숫자의 갯수는 %d 이다.\n",sum);
}
이제 C 공부하기 시작한 초보입니다. 배운 범위에서는 이렇게 하면 되네요.
Ruby
puts ("1".."10000").to_a.join.count("8")
문자열 Range "1" 부터 "10000" 까지를, Array로 변환, Array를 하나의 문자열로 합치고, "8"이라는 문자를 Count 한 후, 결과를 출력한다.
여러분 루비하세요. 자바가 한문이라면 루비는 한글입니다.
Java로 풀어보았습니다.
각 자리수에 대해 8인지 검사하고 8이면 cnt값을 하나씩 증가시켜서 8의 개수를 구하는 코드입니다.
class Count8 {
public static void main(String[] args) {
int cnt = 0;
for(int i = 1; i < 10000; i++ ) {
if( i % 10 == 8 ) cnt++;
if( (i / 10) % 10 == 8 ) cnt++;
if( (i / 100) % 10 == 8 ) cnt++;
if( (i / 1000) % 10 == 8 ) cnt++;
}
System.out.println("result : " + cnt);
}
}
print ''.join(str(x) for x in range(1, 10001)).count('8')
Python(2.7.9)으로 작성하였습니다.
결과는 4,000으로 확인되었습니다.
int 값을 String으로 변환하여 8을 찾아야겠다고 생각했는데, 길가의풀님도 그렇게 하셨네요! 파이썬 초보인데 길가의풀님 코드의 count('8')을 보고 저도 적용해보았습니다. 뭔가 find() 메소드가 있을거라 생각했었습니다 ^^;
>>> str(list(range(1,10001))).count('8')
import java.util.stream.IntStream;
public static void main(String[] args) {
System.out.println(String.format(">> %d", foo()));
}
public static long foo(){
//return IntStream.range(1, 10000).map(x -> String.valueOf(x).replaceAll("[0-79]", "").length()).sum();
return IntStream.rangeClosed(1, max)
.map(x -> (int)(String.valueOf(x).chars().filter(ch -> ch == '8').count()))
.sum();
}
java 8 버전입니다.
Sub Main()
Console.WriteLine("Result: " & (From c As Char In String.Join("", Enumerable.Range(1, 10000)).ToArray Where c = "8"c Select c).Count)
Console.ReadLine()
End Sub
Linq를 이용했습니다.
정답: 4000
Stopwatch sw1 = Stopwatch.StartNew();
int cnt = Enumerable.Range(1, 10000).Sum(k => k.ToString().Count(z => z == '8'));
sw1.Stop();
Console.WriteLine($"Elapsed MillSecond : {sw1.ElapsedMilliseconds}, Value : {cnt}");
Elapsed MillSecond : 4, Value : 4000
-- ORACLE SQL
SELECT SUM(CNT)
FROM (SELECT LENGTH(TO_CHAR(LEVEL)) - NVL(LENGTH(REPLACE(TO_CHAR(LEVEL),'8','')),0) CNT
FROM DUAL
CONNECT BY LEVEL <= 10000)
;
'''
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
'''
# for문으로 하나하나 확인
count = 0
for i in range(10000): # [0...9999]
for j in str(i):
if j == '8':
count += 1
print(count)
# 또는
print(str(list(range(10000))).count('8'))
# 8*** -> 000~ 999 -> 1000개
# *8** -> 000~ 999 -> 1000개
# **8* -> 000~ 999 -> 1000개
# ***8 -> 000~ 999 -> 1000개
# 4000개가 답이다.
result = 0
for i in range(1, 10000):
a = list(str(i))
for m in a:
if "8" in m:
result += 1
print(result)
sum=0
for i in range (1,10001):
ii=str(i)
for j in range (0,len(ii)):
if int(ii[j])==8:
sum=sum+1
print (sum)
# List comprehension 이용
nums = [int(a) for x in range(1,10001) for a in str(x)]
count = sum(1 for n in nums if n == 8)
print(count)
C 코드입니다.
#include <stdio.h>
int main()
{
int i;
int count[4] = {1};
int v = 9;
int sum = 1;
for (i = 1; i < 4; i++) {
count[i] = v + count[i - 1] * 10;
v *= 10;
sum += count[i];
}
printf("count of 8 from 1 to 10,000: %d\n", sum);
return 0;
}
Python 으론 이렇게 단순한데요. 근데 이렇게 간단한 답을 원하는게 아니라 어떻게 풀어야 하는지 방식을 설명해야 될것 같습니다.
list=""
for i in range(1,10000): list = list + str(i)
print list.count('8')
PHP입니다.
<?php
$c = 0;
for($i=0;$i<10000;$i++){
for($j=0;$j<strlen($i);$j++){
if(substr($i,$j,1)==8){
$c++;
}
}
}
echo $c;
?>
(총자리수 - 1) * 10 ^ (총자리수 - 2)
예:
100 까지 8 의 총 갯수 -> 2 * 10 ^ 1 = 20
1000 까지의 8 의 총 갯수 -> 3 * 10 ^ 2 = 300
10000 까지의 8 의 총 갯수 -> 4 * 10 ^ 3 = 4000
루푸 없이 입력한 숫자까지 갯 수 구하는 프로그램 입니다.
#include "stdafx.h"
#include <math.h>
int Get8Count(int nValue)
{
int nCount = 0;
int nDigit = log10((double)nValue);
if(nDigit ==0 || nValue ==0)
return nValue >=8;
int nLast = ((int)(nValue/pow(10.,nDigit))) ;
nCount += nDigit * pow(10.,(nDigit-1)) *nLast;
if(nLast == 8)
nCount++;
return nCount+Get8Count(nValue%(int)(pow(10.,nDigit)));
}
int _tmain(int argc, _TCHAR* argv[])
{
while(1)
{
printf("?");
int nMax = 0;
int nCount = 0;
scanf("%d",&nMax);
printf("\n%d\n",Get8Count(nMax));
}
return 0;
}
c# 입니다.
int cnt = 0;
for(int i = 0 ; i < 10000; i++)
for(int j = 0; j < i.ToString().Length; j++)
if (i.ToString()[j].ToString().Contains("8")) cnt++;
System.Console.WriteLine("cnt : " +cnt);
파이썬입니다.
eightTotal = 0
for numb in range(0,9999):
eightTotal = eightTotal + str(numb).count('8')
print(eightTotal)
def count8():
cnt = 0
for i in range(1, 10001):
cnt += str(i).count('8')
return cnt
def count8_1(sum=0, n=1):
if n>4: return sum
sum = sum*10 + 10**(n-1)
return count8_1(sum, n+1)
def count8_2():
cnt = 0
cur = 1
while cur <= 4:
cnt = (cnt * 10 + 10**(cur-1))
cur = cur+1
return cnt
count = 0
for i in range(10000):
sentence = str(i)
for j in range(len(sentence)):
if sentence[j] == '8':
count+=1
print("%d", count)
Python 한줄 코드보고 놀라움을 감추지 못하고있네요. 저도 언젠가 저런날이 오길...
전 7줄이나... int -> str 으로 변환해서 '8'을 찾았습니다.
cou = 0
for i in range(0, 10):
for j in range(0, 10):
for k in range(0, 10):
for l in range(0, 10):
m=[i,j,k,l]
cou=cou+m.count(8)
print(cou)
약간의 힌트를 얻어 위에처럼 코딩이라고 부르기에 부끄러운 코딩했습니다.
다른 분 보니 파이썬으로 아주 쉽게 했던데..ㅎㅎ
같은 도구를 가지고도 이렇게 비효율적으로 할 수 있다는 제 자신에 놀랐습니다. ㅎㅎ
파이썬입니다. 초보라 한줄로는 안되네요...
count_8 = 0
for num in range(1,10001):
count_8 = count_8 + str(num).count('8')
print("result = %d" % count_8)
결과 값
result = 4000
오늘 밀고가는 자바스크립트와 정규식 조합입니다.
var c = 0;
for(var i = 0 ; i <= 10000 ; i++) {
(i + "").replace(/[8]+/g, function (match) {
c += match ? match.length : 0;
});
}
console.log(c);
와... 풀고 나서 다른 분들 글 보고 경악을 금치 못하겠네요.. 한줄로 퉁이라니 ㅋㅋㅋ
난 뭐 이리 복잡하게 짠거지? ㄷㄷㄷ
def countEight(m):
eightCnt = 0
for i in range(1, m+1) :
eightCnt = eightCnt + checkEight(i)
return eightCnt
def checkEight(i) :
if i > 10 :
if i % 10 == 8 :
return checkEight(i/10) + 1
else :
return checkEight(i/10)
else :
if i == 8 :
return 1
else :
return 0
if __name__ == '__main__':
print countEight(10000)
파이썬으로 간단하게 나타냈습니다.
count = 0
for number in range(1,10001):
for ch in str(number):
if ch == '8':
count += 1
print(count)
//javascript
function test(a){
return (a.toString().length-1)*(a/10);
}
//test
for (var j=0 ; j<10; j++){
var input = Math.pow(10, j);
console.log( "%d -> %d ", input, test( input )) ;
}
결과
1 -> 0
10 -> 1
100 -> 20
1000 -> 300
10000 -> 4000
100000 -> 50000
1000000 -> 600000
10000000 -> 7000000
100000000 -> 80000000
1000000000 -> 900000000
def count_n(num, n):
tot_count = 0
str_n = str(n)
for i in range(0, num + 1):
temp_str = str(i)
tot_count += temp_str.count(str_n)
return tot_count
n = 8
tot_num = count_n(10000, n)
print("total number of %d is %d" %(n, tot_num))
#include <stdio.h>
int count(int n)
{
int temp;
int i;
int count = 0;
for(i = 0; i <= n; i++)
{
temp = i;
while(temp > 0)
{
if(temp % 10 == 8) count++;
temp /= 10;
}
}
return count;
}
int main(void )
{
printf("%d\n", count(10000));
return 0;
}
길이는 길지만, 하나하나 루프 돌리면서 개수를 세는 것보다는 훨씬 빠르게, 10^20 이상의 큰 숫자에서도 개수를 구할 수 있는 코드입니다. ( by Python )
class ec_2(object):
"""second algorithm : can calculate faster than ec_1 algorithm,
regardless of the magnitude of the given number.
used the fact that 10**n contains n*10**n-1 of 8."""
def __init__(self,k):
self.k = k
def check(self):
key = str(self.k)
n = len(key)-1
eight = 0
i=0
while i<len(key):
if int(key[i])<8:
eight += int(key[i])*(n-i)*(10**(n-i-1))
i += 1
elif int(key[i])==9:
eight += 9*(n-i)*(10**(n-i-1))
eight += 10**(n-i)
i += 1
else:
eight += 7*(n-i)*(10**(n-i-1))
if i==n:
eight += 1
else:
eight += self.k % 10**(n-i)
i = n+2
return eight
가장 단순한 방법으로 하였습니다. 다른 분들의 방법을 보니, 대단하신 분들이라고 느껴지네요.
1~10000까지 모든 숫자를 일렬로 세우고, 문자열로 변환후, 8을 세는 방법도 있겠네요.
import unittest
def method1():
count = 0
for i in range(1, 10001):
if str(i).count("8") > 0:
count += str(i).count("8")
return count
def method2():
count = 0
for i in range(1, 10001):
count += str(i).count("8")
return count
class TestCount8(unittest.TestCase):
def test_methods(self):
self.assertEqual(method1(), 4000)
self.assertEqual(method2(), 4000)
if __name__ == "__main__":
unittest.main()
java 입니다.
int totalCnt = 0;
// 1부터 10000까지 루프
for(int i=1; i<10000; i++){
// i를 String 형태로 변환
String str = String.valueOf(i);
// String형태에서 8문자가 있는지 확인
if(str.contains("8")){
// 8이 있다면 현재 변환된 String의 길이값으로 루프
for(int j=0; j<str.length(); j++){
// 문자형태로 변환해서 8인지 확인
if('8' == str.charAt(j)){
totalCnt++;
}
}
}
}
System.out.println("총 " + totalCnt + "개");
1~10000범위의 숫자를 문자열, 즉 str로 하여금 싱글쿼터 안에 8을 넣음으로써 문자열으로 인식하여 8의 갯수를 카운트 합니다.
>>> print str(range(1, 10000)).count('8')
4000
c입니다. 숫자 8을 어떻게 세지 고민하다가 char형으로 바꾼다음에 세는 방법을 썼는데... 다른 분들의 풀이를 보고 나서야 %를 사용하면 된다는 사실을 깨달았네요ㅜㅜ
#include <stdio.h>
#include <stdlib.h>
#define MAX 10000
int main()
{
int number=0, i, j=0, k;
int count=0;
char buffer[10]={0,};
for(i=0;i<MAX;i++)
{
number++;
itoa(number,buffer,10);
while(buffer[j])
{
if(buffer[j]=='8')
{count++;}
j++;
}
for(k=0;buffer[k];k++)
{
buffer[k]='\0';
}
j=0;
}
printf("1부터 %d까지 8의 개수는 %d개입니다.\n", MAX, count);
return 0;
}
int count = 0;
for (int i = 1; i <= 10000; i++) {
if (i % 10 == 8)
count++;
if ((i / 10) % 10 == 8)
count++;
if ((i / 100) % 10 == 8)
count++;
if (i / 1000 == 8)
count++;
}
System.out.println(count);
다른분들 코드 대단하네요 ..ㄷㄷ
// java
// n = 10, 100, 1000 ...
// System.out.println(google(10000));
public static int google(int n) {
return n==0 ? 0 : 10 * google(n/10) + n/10;
}
오토핫키입니다. 프로그램언어선택란에도 없네요..그래서 해 봤습니다..
loop,10000
수나열.=A_Index
숫자8만모음:=RegExReplace(수나열,"[^8]")
MsgBox,% strlen(숫자8만모음)
#import <Foundation/Foundation.h>
@interface Eight : NSObject
{
int count; // 숫자의 갯수
int num; // 어떤숫자를 확인할지
}
@end
@implementation Eight
-(id)initMember
{
if( (self = [ super init ]) )
{
count = 0;
num = 8; // 8이 몇개인지 확인하기 위해 8로 초기화
}
return self;
}
-(void)LoopMethod:(int)var
{
while( var-- ) // 입력받은값이 0보다 클동안 반복
{
[ self CountMethod: var ]; // 입력받은수에서 8의 갯수 확인
}
}
-(void)CountMethod:(int)var
{
while( var > 0 ) // var/10 이 0이면 1의자리한개만 남은상황이므로 검사종료.
{
if( num == var % 10 ) count++;
// 10으로 나누면 1의자릿수만 남게되는데 그게 8인지확인
var = var / 10;
} // 10으로 나누면 1의자리는 없어지고 10의자리가 1의자리가 된다.(몫만 취하므로)
}
-(int)count { return count; }
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
Eight * obj = [ [ Eight alloc ] initMember ];
[ obj LoopMethod: 10000 ];
NSLog(@"result = %i", [ obj count ] );
}
return 0;
}
puts ("1".."10000").to_a.join.count("8")
위의 김PD님이 작성한 루비코드와 같은데 아예 처음부터 array로 시작합니다.
puts Array(1..10000).to_s.count('8')
puts Array(1..10000).join.count('8')
Scala; Stream, View 활용
// div10(2553) = [2553, 255, 25, 2, 0, 0, 0, ...]
def div10(n: Int): Stream[Int] = n #:: div10(n / 10)
// count8(8138) = 2
def count8(n: Int): Int = div10(n).takeWhile(_ != 0).count(_ % 10 == 8)
println((1 to 10000).view.map(count8).sum)
파이썬 입니다. 풀고 보니 이미 훨씬 아름다운 코드들이 많이 올라와 있네요 ^^;; 그래도 한번 올려 봅니다~~~
total = 0
for x in range (1,10001):
y = str(x)
num = y.count('8')
total += num
print(total)
문자열로 한자리씩 끊어 처리하는 방법이랑 각 자리수로 계산 하는 방식 2가지로 해봤습니다. JAVA 코드입니다~
package my_test;
public class T {
public static void main(String[] args) {
int su=10000;
System.out.println("자리수 계산 방식:"+eight_num(su));
System.out.println("문자열 계산 방식:"+eight_str(su));
}
/**
* 자리수 계산 방식
*/
public static int eight_num(int num){
int result=0;
for(int i=0;i<=num;i++){
for(int j=i;0<j;){
if(j%10==8){
result++;
}
j/=10;
}
}
return result;
}
/**
* 문자열 계산 방식
*/
public static int eight_str(int num){
int result=0;
for(int i=1;i<=num;i++){
String temp= String.valueOf(i);
for(int j=0;j<temp.length();j++){
if('8' == temp.charAt(j)){
result++;
}
}
}
return result;
}
}
using System;
class Program
{
static void Main(string[] args)
{
int numberEightCount = 0;
for (int i = 1; i <= 10000; i++)
{
char[] digits = i.ToString().ToCharArray();
foreach (var aDigit in digits)
{
if (aDigit == '8')
{
numberEightCount++;
}
}
}
Console.WriteLine("numberEightCount = " + numberEightCount);
}
}
objective c 풀었습니다. 문자열로 변환이후 각 자리수를 어떻게 구해야 하나 생각하느라 시간이 좀 걸렸네요
- (int) CountNumber:(NSString *)num
{
self.countNum = 0;
for(int i = 1; i<=10000; i++)//1~10000까지 숫자를 한번씩 계산합니다
{
NSString *temp = [NSString stringWithFormat:@"%d", i];
//문자열로 전환
for(int j=0; j < temp.length; j++)//그 전환한 문자열의 자릿수 만큼 반복합니다
{
if('8' == [temp characterAtIndex:j])//각 자리수를 체크
{
countNum++;
}
}
}
return countNum;
};
//main
CountNumber *myCountNum = [[CountNumber alloc] init];
[myCountNum CountNumber:@"8"];
NSLog(@"%d", myCountNum.countNum);
//결과
CodingDojang[965:303] 4000
성능을 위해 StringBuilder를 사용했습니다
public class Main {
public static void main(String[] ar){
int cnt = 0;
StringBuilder s = new StringBuilder();
for(int i = 1; i <= 10000; i++){
s.append(i);
}
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == '8')
cnt++;
}
System.out.println(cnt);
}
}
package Coding;
public class coding2 {
public static void main(String args[]){
int ard=0; // 나누어줄 값
int res=0; // 계산의 결과
int cor=0; // 결과값, 갯수
int incr=88; // 구해야할 값의 한계
for(int j=0;j<=incr;j++){
ard = j;
for(int i=0; i<=ard;i++){
res = ard % 10;
ard /= 10;
if(res == 8){
++cor;
}
res = 0;
}
System.out.println(cor);
}
}
}
total = 0
for x in str(range(1,10001)):
for n in x:
if n == '8':
total += 1
print total
'길가의 풀'님의 풀이를 파이썬으로 더 풀어봤습니다. 더 길어서 의미는 없습니다만ㅎ
public class CountEightMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "";
char cArray[] = null;
long cnt = 0;
for(int i = 1; i <= 10000; i++) {
s = Integer.toString(i);
cArray = s.toCharArray();
for (int j = 0; j < cArray.length; j++) {
if (cArray[j] == '8') {
cnt = cnt + 1;
}
}
}
System.out.println(cnt);
}
}
#include <iostream>
using namespace std;
void main() {
int num = 10000;
int count = 0;
for (num; num != 0; num--) {
int i = num;
while (i >= 8) {
if (i % 10 == 8)
count++;
i /= 10;
}
}
cout << count << endl;
}
일에서 천의 자리에 8을 꽂아넣고 나머지 숫자조합이 가능한 1000개씩 총 4천개가 됩니다만, 파이썬으로는 정직하게 다음과 같이 구해보았습니다.
print sum((str(x).count('8') for x in range(1, 10000+1)))
각 자리에 8이 출현할 경우의 수는..
[10, 10, 10, 1].reduce(:*) + [10, 10, 1, 10].reduce(:*) + [10, 1, 10, 10].reduce(:*) + [1, 10, 10, 10].reduce(:*)
[10, 10, 10, 1].reduce(:*) + [10, 10, 10, 1].reduce(:*) + [10, 10, 10, 1].reduce(:*) + [10, 10, 10, 1].reduce(:*)
[10, 10, 10, 1].reduce(:*) * 4
10 * 10 * 10 * 1 * 4
4000
이네요.
그냥 아무생각없이 풀면
('8'..'9998').map {|s| s.scan(/8/).size }.reduce(:+)
펄입니다
$_=$ARGV[0];my$s=join("",1..$_);grep {$_==8},(split //,$s)
리눅스 쉘에서 다음과 같이 입력합니다
perl -e '$_=$ARGV[0];my$s=join("",1..$_);grep {$_==8},(split //,$s)' 10000
4000
def counter(n, max):
#print n
#print max
cnt = 0
for i in range(1, int(max)+1):
for c in str(i):
if str(n) == c:
cnt +=1
return cnt
print "카운팅 할 숫자와 최대값을 입력하세요! (예: 3,20) : "
n,max = raw_input().split(',')
cnt = counter(n,max)
print ('1부터 %s 까지 숫자 중에서 %s 은(는) 총 %s 번 나왔습니다.') % (max,n,cnt)
파이썬2.7 입니다. 답은 4000개 맞게 나오는데, 10,000까지 8만 카운트 하는게 아니라 입력받은 수 내에서 카운트 하게끔 해봤습니다.
coding by python beginner
cnt = 0
for i in range(10000):
for s in str(i):
if s == '8': cnt += 1
print(cnt)
#!/usr/bin/python
# -*- coding: euc-kr -*-
# -*- coding: utf-8 -*-
# -*- coding: ko_KR.eucKR -*-
def main():
cnt = 0
for i in range(1,10000):
sss = str(i)
for j in range(0,len(sss)):
if sss[j] == '8' :
cnt = cnt+1
print cnt
if __name__ == "__main__":
main()
swift입니다.
import UIKit
var count=0
for(var i=1;i<10001;++i){ for(var j=i;j>0;j /= 10){ if(j%10 == 8){ count++ } } }
print(count)
숫자를 차례대로 문자열로 바꾼다음 그 안에서 8 이라는 숫자를 카운트 합니다.
def string_count(word):
count=0
list=word
for t in list:
if '8' == t:
count=count+1
return count
t_count=0
for i in range(10000):
value=str(i)
if '8' in value:
t_count=t_count + int(string_count(value))
print t_count
python 정규표현식을 이용해서 풀어봤습니다
import re
def main():
list = []
for num in range(10000):
list.append(num)
count = re.findall(r'8',str(list))
print(len(count))
if __name__ == '__main__':
main()
흠 카운트를 숫자 제조하는 느낌으로 제조하면서 생기는 8이라는 숫자를 모조리 세어봤는데 다른분들은 엄청나시군요 ......
package count_8;
public class count8 {
public static void main(String[] args)
{
int count=0;
for(int a=0; a<1; a++){
for(int b=0; b<=9; b++){
for(int c=0; c<=9; c++){
for(int d=0; d<=9; d++){
for(int e=0; e<=9; e++){
if(e==8)
count++;
if(d==8)
count++;
if(c==8)
count++;
if(b==8)
count++;
if(a==8)
count++;
}
}
}
}
}
System.out.println(count);
}
}
Python 3.4.2입니다. 기본에 충실하게 해 보았습니다.
sum8s = 0
for i in range(1,10001) :
for j in str(i) :
if j == '8' :
sum8s += 1
print(sum8s)
public class CountingEight {
private static int count = 0;
public static void main(String args[]){
for(int num = 1 ; num <= 10000; num++){
String numStr = String.valueOf(num);
int sl = numStr.length();
for (int i=0; i < sl; i++){
if ( numStr.charAt(i) == '8') count++;
}
}
System.out.println("count is "+count);
}
}
무식하게 풀어봤습니다
public class CD393 {
public static void main(String[] args){
int answer = 0;
for(int i = 1; i <= 10000; i++){
for(char c : new Integer(i).toString().toCharArray()){
if(c == '8') answer++;
}
}
System.out.println(answer);
}
}
파이썬 3.2.3에서 작성했습니다.
count=0
for x in range(10000):
for n in str(x):
if int(n) == 8:
count=count+1
print(str(count))
TDD로 작성해보았습니다.
public class CountEightsTest {
// with 1 to n numbers
// it should count the number of 8
@Test
public void itSouldCountTheNumberOf8() {
CountNumbers counter = new CountNumbers('8');
assertEquals(0, counter.countRangeFor(1,1));
assertEquals(0, counter.countRangeFor(1,7));
assertEquals(1, counter.countRangeFor(1,8));
assertEquals(1, counter.countRangeFor(1,10));
assertEquals(1, counter.countRangeFor(1,17));
assertEquals(2, counter.countRangeFor(2,18));
assertEquals(8+8, counter.countRangeFor(2,87));
assertEquals(8+8+2, counter.countRangeFor(2,88));
assertEquals(2+3, counter.countRangeFor(887,888));
assertEquals(1+2, counter.countRangeFor(807,808));
assertEquals(2+1, counter.countRangeFor(8008,8009));
assertEquals(0, counter.countRangeFor(1000,1001));
}
class CountNumbers {
private char character;
public CountNumbers(String character) {
this.character = character.toCharArray()[0];
}
public CountNumbers(char character) {
this.character = character;
}
public int countRangeFor(int start, int end) {
int count = 0;
for(int i = start; i <= end; i++) {
String number = i+"";
int addition =countTheNumberOf(number);
count += addition;
}
return count;
}
private int countTheNumberOf(String string) {
int count = 0;
for (char one : string.toCharArray()) {
if ( one == character ) {
count++;
}
}
return count;
}
}
}
C#으로 작성했습니다. 7에서 9 milliseconds 정도 걸렸습니다.
using System.Linq;
public int CountEights(int n)
{
var sum = 0;
for (int i = 0; i <= n; i++)
sum += i.ToString().Count(e => e.ToString().Contains('8'));
return sum;
}
Using python
print str(range(1,10000)).count('8')
프로그래밍 언어를 사용하면 저렇게 구할 수 있지만 맨 앞에 답을 다신 'Jake kim'님 답변대로 생각을 얼마나 논리적으로 전개시킬 수 있나의 문제같네요 허허
c 언어입니다.
#include <stdio.h>
int main(void)
{
int b = 10000, c = 0, Count = 0, i = 0;
while(b >= 0)
{
i = b;
while(1)
{
c = b%10;
b = (int) b/10;
if((double) c/8==1)
{
Count++;
}
if(b==0)
break;
}
b = i - 1;
}
printf("%d\n", Count);
return 0;
}
arr = []
for i in range(7,9999):
arr += str(i)
sum = 0
for i in arr:
if (int(i) == 8):
sum += 1
print(sum)
아 count라는 함수가 존재하는군요 ㅠ
#include <stdio.h>
int main(void)
{
int i , j , k , l;
int n=0;
for( i = 0 ; i <=9 ; i++)
{
for( j = 0; j <= 9 ; j++)
{
for( k = 0 ; k <= 9 ; k++)
{
for( l = 0 ; l <= 9 ; l++)
{
if( i == 8 )
n++;
if(j==8)
n++;
if(k==8)
n++;
if(l==8)
n++;
}
}
}
}
printf("%d\n",n);
return 0;
}
다른 분들 대단하시네요.. 얼릉 C를 끝내고 다른 언어 공부해야할듯
PHP
<?php
$count = 0; // $count를 숫자화시킨다
for($i=1;$i<=10000;$i++){ // 1부터 10000까지 반복한다
$i = (string)$i; // $i를 문자화시킨다 (이유 : 밑의 $j번째 글자를 불러오기 위해)
for($j=0;$j<strlen($i);$j++){ // 0부터 $i의 글자수 - 1번만큼 반복한다
if($i[$j]=="8")$count += 1; // $i의 $j번째 글자가 8이면 $count를 +1시킨다
}
$i = (int)$i; //$i를 숫자화시킨다.
}
echo $count; // $count를 출력한다.
?>
PHP는 간단하게(?)되네요 ㅋㅋㅋ
#include <iostream>
using namespace std;
int main(){
int count = 0;
int bcd[4] = { 0 };
int num;
for (int i = 1; i < 10000; i++)
{
num = i;
for (int j = 3; j >= 0; j--)
{
bcd[j] = num % 10;
num /= 10;
}
if (bcd[0] == 8)
count++;
if (bcd[1] == 8)
count++;
if (bcd[2] == 8)
count++;
if (bcd[3] == 8)
count++;
}
cout << "8이 나온 횟수 : " << count << endl;
return 0;
}
이렇게 짜봤습니다... 어떤가요?? 제가 생각한 방법은 예를들어 124라는 숫자를 bcd코드로 변환해서 0, 1, 2, 4로 만듭니다 그리고 각 자리의 숫자가 8이면 count를 하나 증가시키는 방법입니다
Go 로 간단히 짜봤습니다.
func main() {
count := 0
for i := 1; i < 10001; i++ {
count += strings.Count(strconv.Itoa(i), "8")
}
fmt.Println(count)
}
Javascript 입니다.
var cnt = 0;
var strNum;
for(var i=1;i<=10000;i++) {
strNum = String(i);
for(var j=0;j<strNum.length;j++){
if(strNum[j] === "8") {
cnt++
}
}
}
console.log(cnt);
Tcl/tk입니다.
set sum 0
set match_num 0
for {set x 1} {$x <= 10000} {incr x} {
set pattern_check [ regexp -all {[8]} $x ]
if { $pattern_check != 0 } {
lappend match_num $pattern_check
}
}
set sum [ expr [ join $match_num "+" ]]
자바 한줄로 해봤습니다. 좀 지저분하네요
IntStream.range(1, 10000).filter(e -> String.valueOf(e).contains("8") ).map(e -> String.valueOf(e).replaceAll("[^8]", "").length()).sum();
{```{.cpp}
#include<iostream>
using namespace std;
int eight(int n);
int count;
int main() {
for(int i = 0; i < 10001; i++) {
eight(i);
}
cout << "8의 개수: " << count << endl;
return 0;
}
int eight(int n)
{
if(n%10 == 8)
count++;
if(n > 10)
eight(n/10);
return count;
} ```
저는 좀 특이하게 ! (? ㅋㅋ)
static void Main(string[] args)
{
int result = 0;
for(int i = 1;i<= 10000;i++)
{
char[] value = i.ToString().ToArray();
for(int z = 0; z<value.Length;z++)
{
if(value[z] == '8')
{
result++;
}
}
}
Console.WriteLine(result);
}
0000부터 9999까지로 생각을 하면 4자리수(숫자 4개)가 10000번 반복되었으므로, 총 사용된 숫자는 4만개. 모든 정수는 동일한 빈도로 사용되었기 때문에 나누기 10 하면, 4000
print ''.join([str(i) for i in range(1,10000)]).count('8')
import re
pat=re.compile('8')
n=''.join([str(i) for i in range(1,10000)])
s=len(pat.findall(n))
print s
using java
public class Main {
public static void main(String[] args) {
int returns = 0;
for(int i = 0; i<10000; i++)
{
String str = String.valueOf(i);
for(int j = 0; j<str.length(); j++)
returns += ("8".equals(String.valueOf(str.charAt(j))))? 1:0;
}
System.out.println(returns);
}
}
#include <stdio.h>
#include <Windows.h>
int main()
{
int sum=0;
for(int i=1;i<10001;i++)
{
for(int j=i;j>0;j/=10)
{
if(j%10 == 8)
{
sum++;
}
}
}
printf("%d",sum);
system("pause");
return TRUE;
}
number_list = ""
for i in range(1,10000):
number_list = number_list + str(i)
print (number_list.count('8'))
public class dojo2
{
public static void main(String[] args)
{
//count from 0 - 10000
int count = 0 ;
for(int i = 0 ; i<10001 ; i++){
String s = Integer.toString(i);
char[] a = s.toCharArray();
for(int j=0;j<a.length;j++){
if(a[j] == '8')
{
count++;
}
}
}
System.out.println("Result: "+count);
}
}
total_count_8 = 0
for number in range (1, 10001):
total_count_8 += str(number).count('8')
print total_count_8
4000
static void Main(string[] args)
{
Console.WriteLine(Answer(8,10000));
}
static int Answer(int findNum,int numMax)
{
string sum = "";
for (int i = 1; i <= numMax ; i++)
{
sum += i;
}
int answer = sum.Length - sum.Replace(findNum.ToString(), "").Length;
return answer;
}
일단 반복문으로 1부터10000까지 범위를 잡고 일의자리숫자 십의자리숫자 백의자리숫자 천의자리숫자를 따로 분리한후 분리한숫자를 8로 나눳을경우 0이나오면 카운트를 1씩증가시키는식으로 짜봤습니다
package dojavn;
public class dsa {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=0;
for(int i=1;i<10000;i++){
int x1=i/1000%10;
int x2=i/100%10;
int x3=i/10%10;
int x4=i/1%10;
if(x1==8){count++;}
if(x2==8){count++;}
if(x3==8){count++;}
if(x4==8){count++;}
}
System.out.println(count);
}
}
public static int count(int number){
int count = 0 ;
for(int i= 1 ; i <=number ; i++){
String temp = i+"";
String[] temp2 = temp.split("");
for( int j = 0 ; j < temp2.length ; j++){
System.out.println(temp2[j]);
if(temp2[j].equals("8")){
count++ ;
}
}
}
return count;
}
void exce7()
{
int count = 0;
for (int i = 0; i <= 10000; i++)
{
int temp = i;
while (temp > 0)
{
if (temp % 10 == 8)
count++;
temp /= 10;
}
}
printf("1에서 10000까지 8의 갯수는 %d개\n", count);
}
def eightcounter(a):
tmp = 0
a = str(a)
for i in range(0, len(a)):
if int(a[i]) == 8:
tmp = tmp + 1
return tmp
summ = 0
for ii in range(0, 10000):
summ = summ + eightcounter(ii)
print(summ)
깊은 생각 없이 단순 코딩을 하고 있었는데...창의적 해법에 반성하게 되네요.
저는 무식하게 for문과 string으로 하는걸 시도해 봤습니다. count method 없이 만들었습니다.
entire_string=""
eights=0
for i in range(1,10001):
entire_string=entire_string+(str(i))
number_list=list(entire_string)
for j in number_list:
if j=="8":
eights=eights+1
else:
continue
print eights
python3입니다. 각 숫자를 문자로 바꾼다음 8을 1로, 다른건 0으로 바꾸고 다 더하였습니다. 다른분들 푸신걸 보니 제가 바보같았네요 ㅜㅠ
print (sum([sum(map(lambda x: (1 if x == '8' else 0), s)) for s in [str(n) for n in range(1, 10001)]]))
<?php
$cnt = 0;
for ($i=0; $i <= 10000; $i++) {
$temp = explode('8', (string)$i);
$cnt = $cnt + (count($temp) -1);
}
echo $cnt;
?>
좀 야매스러운방법이긴 하지만 생각해봣습니다.
#include <iostream>
using namespace std;
int main()
{
int total = 0;
for (int i = 0; i <= 10000; ++i)
{
for (int d = 10; d <= 10000; d *= 10)
{
if (i%d / (d / 10) == 8)
++total;
}
}
cout << total << endl;
return 0;
}
이미 완벽한 답이 나왔으니 전 컴퓨터를 학대하는 방법으로!
lst = []
for i in range(1,10001):
lst.append(i)
result = 0
lst_str = str(lst)
for i in lst_str:
if i == "8":
result += 1
print result
스트링으로 받아서 8을 다 셌습니다. 그냥 머리로 푸신 분들도 계시네요.
Swift 2.1 입니다.
비싼 String 연산을 쓰지않도록 고민해봤습니다.
var count = 0
for i in 1...10000 {
var number = i
while number > 0 {
count += ((number % 10) == 8) ? 1 : 0
number = number / 10
}
}
return count
간단하게는 아래와 같이도 할 수 있겠네요
Range(start: 1, end: 10001).reduce(0) { $0 + String($1).characters.filter { $0 == "8" }.count }
python 3.4
count8 = 0
for i in range(10000):
int2list = list(str(i))
count8 += int2list.count('8')
print(count8)
python
print(sum([str(i).count('8') for i in range(1,10001)]))
haskell
sum $ map (\n->foldr (\x acc->if x == '8' then acc + 1 else acc) 0 (show n)) [1..10000]
c++
#include <stdio.h>
int main() {
int n = 0;
char szNum[4];
for(int i=1;i<10000;++i) {
sprintf(szNum, "%04d", i);
for(int j=0; j<4; ++j) {
if(szNum[j] == '8') {
n += 1;
}
}
}
printf("%d", n);
return 0;
}
결과 4000
Ruby
# one-liner
p ([*1..10000]*'').count '8' #=>4000
# for test
counter = ->num,s {([*1..num]*'').count s}
Test
expect(counter[10000,'8']).to eq 4000
java로 줄여보고 싶었습니다...
public class eight {
public static void main(String... args){
int count = 0;
for(int i = 0 ; i<=10000 ; i++)
count += (" "+i+" ").split("8").length-1; // 배열의 길이로 측정
//split과정에서 8이 끝에 있으면 배열 길이로 계산되지 않으므로 문자열 추가
System.out.println(count);
}
}
i=1
result=0
while i<=10000:
data=list(str(i))
result+=data.count('8')
i+=1
print(result)
Python 3.3
var totalCount = 0
for i in 0..<10000{
let str = String.init(format: "%4d", i)
for ch in str.characters {
if ch == "8" {
++totalCount
}
}
}
print("total \(totalCount)")
한자리 숫자에서 8의 갯수는 1가지.
두자리 숫자에서 8의 갯수는 1*10(십의 자리가 8인 경우) + 9*1(일의 자리가 8인 경우) = 10+9 = 19가지.
비슷한 방법으로, 세자리 숫자에서 8의 갯수는 1*10*10 + 9*1*10 + 9*10*1 = 100+90+90 = 280.
마지막으로, 네자리 숫자에서 8의 갯수는 1*10*10*10 + 9*1*10*10 + 9*10*1*10 + 9*10*10*1 = 1000+2700 = 3700.
따라서, 총합을 구하면 1+19+280+3700 = 4000개.
print(sum(str(x).count('8') for x in range(10001)))
파이썬 3.5.1
public class Count_8 {
public static final int TARGET = 10000;
public static void main(String[] args) {
int i = 1;
int[] result = new int[10];
while (true){
String s = ""+i;
for(int j = 0; j < s.length(); j++){
result[Integer.parseInt(""+(s.charAt(j)))] += 1;
}
i++;
if (i>=TARGET)
break;
}
System.out.println(result[8-1]);
}
}
자바
답은 4000
1~9999 까지 중 첫째자리가 8인 경우 : 나머지 세자리에 0부터 999까지의 수가 올 수 있으므로 총 1000가지 둘째, 셋째, 넷째 자리도 위의 경우와 동일하므로 1000 * 4 = 4000가지
count=0
for i in range(1,10001):
for j in str(i):
if j=="8":
count+=1
print(count)
파이썬 아직 반복문 까지 밖에 몰라서.. 내장 함수도 잘 몰라요.
sum = 0
for i in range(1,10001):
a = []
i = str(i)
for k in range(len(i)):
a.append(i[k])
sum += a.count('8')
print(sum)
답은 4000
JAVA 다음에는 저도 창의적인 방법으로 풀어보려고 노력해 볼께요~ 지저분하지만 올립니다 :)
public class Goolgle_num8 {
static public void main(String arg[]) {
Integer num;
int count = 0;
String N = "8" ;
for (int i = 1; i <= 10000; i++) {
num = i;
for (int j = 0; j < num.toString().length(); j++) {
System.out.println( num.toString().charAt(j) );
if (num.toString().charAt(j) == N.charAt(0) ) {
count++;
}
}
}
System.out.println( "the count of 8 from 1 to 10000 : " + count );
}
}
결국 모든 자리에서 1000개씩 등장하네요.
python 코드로 보면
def countDigitInRange(beg, end, digit):
return sum([str(x).count(str(digit)) for x in range(beg, end)])
print countDigitInRange(1,10000,8)
$ 4000
파이썬 3.5로 작성되었습니다.
sum = 0
for i in range(10001):
sum += str(i).count('8')
print(sum)
굉장히 직관적으로 풀었습니다.
숫자 1~10,000까지 문자로 바꾸고 '8'을 카운터하는 방법으로 풀었습니다.
부족한 점이 많습니다. 감사합니다.
#include <iostream> #include <string> #include <sstream> using namespace std; // 10000까지밖에 없다는 점에서 그냥 // brute force로도 빨리 해결가능. string toString(int n){ stringstream ss; ss << n; return ss.str(); } int main(){ int cnt = 0; for (int i = 1; i <= 10000; i++){ string s = toString(i); for (int j = 0; j < s.size(); j++){ if (s[j] == '8') ++cnt; } } cout << cnt << endl; return 0; }
brute force code
PHP 함수로 풀어봤어요 ㅎ
$sum = 0;
for($i=1; $i<=10000; $i++) {
$str = array_count_values(str_split((string)$i));
$sum += $str[8];
}
echo $sum;
#include <stdio.h>
int main(void)
{
int i, temp, count;
count = 0;
for (i = 1; i < 10001; i++) {
temp = i;
while (i >= 10) {
if (i % 10 == 8) {
count++;
i /= 10;
}
else {
i /= 10;
continue;
}
}
if (i == 8)
count++;
i = temp;
}
printf("1 ~ 10000까지 8이라는 숫자가 나오는 횟수: %d\n", count);
return 0;
}
C언어로 작성했습니다. 좀 더 단순하게 짜고싶은데.. 연습 좀 해야겠습니다. ㅎㅎ
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
count := 0
for i := 1; i <= 10000; i++ {
count += strings.Count(strconv.Itoa(i), "8")
}
fmt.Print(count)
}
int box[] = new int[10];//각 숫자를 저장할 공간
for (int i = 1; i <= 10000; i++) {
box[i%10]++;//일의 자리
if (i>=10) box[i/10%10]++;//십의 자리
if (i>=100) box[i/100%10]++;//백의 자리
if (i>=1000) box[i/1000%10]++;//천의 자리
if (i==10000) box[i/1000%10]++;//천의 자리
}
System.out.println(box[8]);
#include <iostream>
int main(void)
{
int count = 0;
for (int i = 0; i < 10000; i++) {
for (int j = i; j > 0; j /= 10) {
if (j % 10 == 8)
count++;
}
}
std::cout << count << std::endl;
return 0;
}
4000이 나오네요
eightCount = 0
for n in range(1, 10001) :
while n > 0 :
if n % 10 == 8 :
eightCount = eightCount +1
n = n // 10
아.. 단순히 갯수만 카운팅 하면 되는거였군요
저는 8888 갯수 4개 이런식로 다 찍으라는 말인줄 알고...
8이 들어가는 것 마다 다찍어 내고 총 갯수도 나오게 했네요
역시 문제를 재대로 보는 능력부터 길러야 겟어요 ㅜㅜ
```{.java}
public static void main(String[] args) {
final int MAX =10000;
int number_8_conut=0;
int total_number_8_count=0;
for(int i =0; i<=MAX; i++){
String AllNumber = String.valueOf(i);
if(AllNumber.contains("8")){
for(int j=1;j<=AllNumber.length();j++){
if (AllNumber.charAt(j-1)=='8') {
number_8_conut +=1;
total_number_8_count +=1;
}
}
System.out.println(AllNumber+" 갯수 :"+number_8_conut+"입니다. ");
number_8_conut=0;
}
}
System.out.println("8의 총 갯수는 :"+total_number_8_count+"개 입니다.");
}
```
0~9 : 1개 0~99: 1 * 10 + 110 =20 0~999: (1 * 10 + 110) * 10 + 100 = 300 // 자릿수 개수 * 10^(자릿수-1) n*10^(n-1) : n = 4 => 4000개
def eight(n):
nstring=str(n)
nlist=[]
for k in range(0, len(nstring)):
nlist.append(nstring[k])
#print(nlist)
return nlist.count('8')
result=0
for k in range(1, 10001):
result+=eight(k)
print(result)
별해) 8의 개수와 상관 없으므로 10000을 0000으로 보아서, 범위를 0000~9999로 생각해도 무방함. 0000 0001 0002 ... 9999 까지 4*10000 매트릭스에 늘여쓰면 모두 40000개의 숫자가 쓰임. 이 때, 수의 분포는 '균질적'이므로 0~9까지 쓰인 숫자의 개수는 똑같음. 따라서 40000/10=4000
#Google Problem My Code.py
result = 0
for i in range(10000):
for j in str(i):
if j == '8':
result+=1
print(result)
단순하게 코드로만 풀어야지 생각하고 있었는데 Best 댓글을 보니까 감탄이 나오네요
C++로 코딩했습니다.
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int count = 0;
for (int i = 1; i <= 10000; ++i)
{
char temp[6] = {0};
sprintf(temp, "%d", i);
for (int j = 0; j < strlen(temp); ++j)
{
if (temp[j] == '8')
count++;
}
}
cout << count << '\n';
return 0;
}
int count=0;
for(int w = 0 ; w<10 ; w++){
for (int q = 0; q < 10; q++) {
for (int o = 0; o < 10; o++) { // 십자리
for (int k = 0; k < 10; k++) { // 십자리
if (w == 8)
count++;
if (q == 8)
count++;
if (o == 8)
count++;
if (k == 8)
count++;
}
}
}
}
System.out.println(count);
}//main
}
파이썬으로 해봤습니다.
su = 0
for x in range(1,10001):
a = str(x)
b = a.count('8')
su += b
print(su)
1부터 10000까지 숫자를 하나씩 문자열로 바꾸고, 그 문자열에서 '8'이라는 문자를 찾아 세는 코드입니다. 답은 4000!!
#def_name : count_8 / input : start, last / output : couting of 8 / type of result : number
# what do i need to solve this problem?
# split every numbers into one number
# and check whether it is 8 or not
def count_8(start,last):
count = 0
for num1 in range(start,last+1):
if len(str(num1)) == 1 and num1 == 8:
count += 1
else:
for num2 in str(num1):
if str(num2) == '8':
count += 1
return count
print count_8(1,10000) # result : 4000
print str(range(1,10001)).count("8")
코드 결과는 4000 나왔습니다.
이론적으로는 각 자리의 숫자를 그룹이라고 생각해서 한 자리씩 카운팅 하면 될것같습니다. 천의 자리에 8이 있을 때를 그룹a ... 일의 자리에 8이 있을 때를 그룹d라고 생각하면 각 그룹에 남는 숫자칸이 3칸이고 각 숫자칸에 0~9 (10)개가 들어갈 수 있으니 경우의 수가 101010 = 1000으로 각 그룹당 1000개의 경우가 있으므로 1000*4 = 4000이 되는것 같습니다.
int solution()
{
int k=0,j=0,iCnt=0,iSum=0;
char byTmp[8];
for(k=0; k<10000; k++)
{
iCnt=0;
memset(byTmp, 0x00, sizeof(byTmp));
sprintf(byTmp, "%d",k);
for(j=0; j<strlen(byTmp); j++)
{
if(byTmp[j] == '8')
iCnt++;
}
iSum += iCnt;
}
printf("result : [%d]\n",iSum);
return 1;
}
result : [4000]
구글이라 그래서 창의력을 요구할 줄 알았는데, 그냥 기초적인 단순한 문제였네요..
public void CountEIGHTOneToTenThousand()
{
int cnt9 = 0;
for (int i = 1; i <= 10000; i++)
{
string Num = Convert.ToString(i);
foreach (char num in Num)
{
if (num == '9')
cnt9++;
}
}
Console.WriteLine(cnt9);
}
비슷한 문제가 하나 있었는데, 그 코드를 재활용한겁니다
int main(void){ int count=0; int i,temp;
for(i=1;i<=10000;i++){
for(temp=i;;){
(temp%10==8)&&count++;
if(temp/10==0)break;
else temp/=10;
}
}
printf("%d", count);
}
Javascript ES6 style 로 풀어봤습니다. loop 돌리는거 싫어해서... pure function으로 짰습니다.
function countEight (number) {
let array = Array.from(new Array(number), (x,i) => i + 1)
return array.join("").split("8").length-1;
}
#include <stdio.h>
#include <stdlib.h>
void main(void) {
int count = 0;
int size = 0;
for(int i = 0 ; i < 10000 ; i++) {
if(i / 1000 == 8)
count++;
if((i%1000 / 100) == 8)
count++;
if(((i%1000)%100 / 10) == 8)
count++;
if((((i%1000)%100)%10) == 8)
count++;
}
printf("%d\t", count);
}
Array.apply( null, Array( 10000 ) ).map( ( v, i ) => { return i } ).join( "" ).match( /8/g ).length
Javascript로 파이썬처럼 짜봤습니다.
파이썬하고 루비 코드가 멋있네요 ㅎ
다들 정말로 대단하시네요.. 여기서 count도 배우고, 신기한 아이디어들도 얻고 갑니다. 감사합니다.
#1부터 10,000까지 8이라는 숫자가 몇 번 나오는가?
a = list(range(1,10001))
b = ""
for i in a:
b += str(i)
c = 0
for i in b:
if eval(i) == 8:
c += 1
else:pass
print(c)
i=1
k="8888"
sum=0
while i < 10000:
j = str(i).zfill(4)
cn1 = int(not bool(int(j[0]) ^ int(k[0])))
cn2 = int(not bool(int(j[1]) ^ int(k[1])))
cn3 = int(not bool(int(j[2]) ^ int(k[2])))
cn4 = int(not bool(int(j[3]) ^ int(k[3])))
sum = sum + cn1 + cn2 + cn3 + cn4
i=i+1
print(sum)
Java 풀이
public class Google {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 10000;
int result = 0;
for(int i = 1; i <= n; i++){
result += countEight(i);
}
System.out.println(result);
}
public static int countEight(int num){
int cnt = 0;
while(true){
cnt += (num % 10 == 8) ? 1 : 0;
if(num / 10 == 0){
break;
}
num = num / 10;
}
return cnt;
}
}
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
int main(void) {
int n, count =0;
for (int i = 1; i < 10000; i++) {
n = i;
while (n) {
if (n % 10 == 8) {
count++;
}
n = n / 10;
}
}
printf("num 8 : %d\n", count);
system("pause");
return 0;
}
c언어로 작성했어요```{.c}
int main() { int arr[5] = { 0, }; int j, count = 0, i = 10001;
while (i--)
{
arr[4] += 1;
j = 5;
while (j--)
{
if (arr[j] == 10)
{
arr[j - 1] += 1;
arr[j] = 0;
}
if (arr[j] == 8)
{
count++;
}
}
}
printf("%d", count);
} ```
numbers = range(0,10000)
eights = []
for i in numbers:
if '8' in list(str(i)):
result = list(str(i)).count('8')
eights.append(result)
print(sum(eights))
Python 3.5.2
public class question { public static void main(String[] args) {
int segi = 0;
for (int i = 1 ; i <= 10000 ; i++)
{
String num_c = ""+i;
for (int j = 0 ; j <= num_c.length() ; j++)
{
if ((int)(i/Math.pow(10, j))%10 == 8)
{
segi++;
System.out.println(i);
}
}
}
System.out.println(segi);
}
}
//java
Java
System.out.println(IntStream.rangeClosed(1, 10000).map(i -> (int)String.valueOf(i).chars().filter(j->j=='8').count()).sum());
4000
N을 10으로 나누면서 나머지 8을 체크하는 방식입니다.
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CountNumberEight {
public static void main(final String[] args) {
}
public int countNumberEight(final int n) {
int count = 0;
for(int i = 1; i <= 10000; i++) {
for(int j = i; j > 0; j /= 10) {
if(j % 10 == 8)
count++;
}
}
return count;
}
@Test
public void testCountNumberEight() {
assertEquals(400, countNumberEight(10000));
}
}
문제의 설명을 그대로 옮겨적는.. brute force ! :-)
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
int sum = 0;
for (int i = 1; i <= 10000; i++) {
sum += count8(i);
}
return sum;
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
int count8(int n) {
int count = 0;
while (n > 0) {
if (n % 10 == 8) {
count++;
}
n /= 10;
}
return count;
}
public class Google1 {
public static void main(String[] args) {
char num[] = new char [4];
int cnt = 0;
for(char i='0'; i<='9'; i++){
num[0]=i;
for(char j='0'; j<='9'; j++){
num[1]=j;
for(char k='0'; k<='9'; k++){
num[2]=k;
for(char m='0'; m<='9'; m++){
num[3]=m;
if(i=='8'){cnt ++;}
if(j=='8'){cnt ++;}
if(k=='8'){cnt ++;}
if(m=='8'){cnt ++;}
}
}
}
}
System.out.println(cnt);
}
}
가장 원시적인 방법으로 풀었습니다.. 메모리 엄청 잡아먹겠네요.. 다른 방법으로도 풀어보겠습니다..
//java
int count=0;
for(int i=0;i<10000;i++){
if(i%10==8)count++;
if(i/10%10==8)count++;
if(i/100%10==8)count++;
if(i/1000%10==8)count++;
}
System.out.println(count);
var cnt = 0;
var arr;
for(i=0;i<10000;i++) //만번동안
{
arr = i.toString().split('8'); //숫자를 문자로 바꾼다음 8을 기준으로 토막을 칩니다.
if(arr.length > 1){ //토막친 배열의 길이를 봅니다. 토막칠게 없으면 1입니다.
cnt = cnt + (arr.length - 1); //토막친다음 1 뺀 것이 8의 갯수이므로, cnt 변수에 담습니다.
}
}
alert(cnt);
javascript 소스를 그냥 올렸더니 바로 XSS 되버리네요. 게시판 올릴때 특수문자 이스케이핑 처리 해야할것 같아요
#include <stdio.h>
#include <string.h>
int found_eight_num(int num);
int main()
{
int i=0;
int total_cnt=0;;
for(i=0; i<10000;i++)
{
total_cnt += found_eight_num(i);
}
printf("Total Cnt : %d\r\n",total_cnt);
}
int found_eight_num(int num)
{
char temp_num[5];
int str_len,ret_cnt=0;
sprintf(temp_num,"%d",num);
str_len = strlen(temp_num);
for(int i=0;i<str_len;i++)
{
if(temp_num[i] == '8') ret_cnt++;
}
return ret_cnt;
}
counter = 0
for i in range(1, 10001):
for digit in str(i):
if digit is '8' :
counter += 1
print counter
/ JAVA 로 작성했습니다. / -- 그린구름님의 재귀호출 코드에 비하면 효율이 많이 떨어지네요. ^^
public class CountNumber {
public static void main(String[] args) {
int startNum = 1;
int endNum = 10000;
int num = 8;
long lStartTime = System.currentTimeMillis();
int retCnt = countNumber(startNum, endNum, num);
long lDuration = System.currentTimeMillis() - lStartTime;
System.out.println(String.format("Elapsed Time: %.3f seconds", lDuration/ 1000.0f));
System.out.println(String.format("%d ~ %d -> %d(Counting:%d)", startNum, endNum, num, retCnt));
}
/**
* 인자로 입력받은 시작, 종료숫자 내에 세번째 인자의 숫자가 몇개 들어있는지 카운트
*/
public static int countNumber(int startNum, int endNum, int number) {
int retCnt = 0;
String num = String.valueOf(number);
String n = "";
for (int i = startNum; i < endNum; i++) {
n = String.valueOf(i);
while (n.indexOf(num) >= 0) {
retCnt++;
n = n.substring(n.indexOf(num)+1);
}
}
return retCnt;
}
}
안녕하세요 처음 가입한 신참입니다. 숫자를 문자로 바꾸면 9876 => "9876" 되고 "9876" 은 [9],[8],[7],[6] 가 저장된 배열입니다. (자바스크립트에선 그렇습니다.) 각 숫자를 문자로 바꾼후 0부터 배열방 번호를 참조, 방의 내용이 "8"과 같으면 sumNum 을 1씩 올려 줍니다.
var sumNum = 0;
for (var i = 0; i < 10000; i++) {
var tmp =i.toString();
for(var j =0; j<tmp.length; j++){
if(tmp[j]=="8"){
sumNum++;
}
}
}
console.log(sumNum); // 결과로 4000 이 나옵니다.
def f(n):
li = []
li.append(int(n/10000))
li.append(int(n/1000)-10*int(n/10000))
li.append(int(n/100)-10*int(n/1000))
li.append(int(n/10)-10*int(n/100))
li.append(n%10)
return li
a = 0
for i in range(1, 10001):
a += f(i).count(8)
print('10000까지 8의 개수: %s' % (a))
public class Practice {
public static void main(String[] args) {
int cnt=0;
for(int i=1;i<=10000;i++){
String str=Integer.toString(i);
char[] c=str.toCharArray();
for(int j=0;j<c.length;j++){
if(c[j]=='8') cnt++;
}
}
System.out.println(cnt);
}
}
자바로 풀어봤습니다 ㅎㅎ 재밌네요~
int Count = 0; for(int i = 1;i<=10000;i++) { char[] number = i.ToString().ToCharArray();
for (int k = 0; k < (i.ToString().Length) ; k++)
{
if (number[k] == "8".ToCharArray()[0])
{
Count++;
}
}
}
밖에 생각이..
print(sum([1 for i in range(1,10001) for j in str(i) if j == '8']))
#### 2016.12.04 D-445 ####
다들 정말 대단하네요.. ㅠㅠㅠ
public class EightCounter {
private static int totalCount = 0;
public static void main(String[] args) {
for (int i = 1; i <= 10000; i++) {
countEight(i);
}
System.out.println(totalCount);
}
public static void countEight(int maxNumber) {
if (maxNumber % 10 == 8) {
totalCount++;
}
if (maxNumber > 10) {
countEight(maxNumber / 10);
}
}
}
if name == "main":
strTotal = ''
for ii in range(1, 10000):
strTotal = strTotal + str(ii)
print (strTotal.count('8'))
public class Ex_7 {
public static void main(String[] args) {
Eight e = new Eight();
e.count();
}
}
class Eight{
void count(){
int count = 0;
for (int i = 1; i <=10000; i++) {
int num = i;
if (num%10==8) {
count++;
}
while(num>10){
num = num/10;
if (num%10==8) {
count++;
}
}
}
System.out.println(count);
}
}
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int i=1; i<=10000; i++){
int num = i;
while(num!=0){
if(num%10 == 8)
sum += 1;
num /= 10;
}
}
System.out.println(sum);
}
}
public class Eight {
static int count = 0;
public static void main(String[] args) {
IntStream.rangeClosed(1, 10000).forEach(num -> {
String.valueOf(num).codePoints().forEach(number -> { if(number - 48 == 8) count++; });
});
System.out.println(count);
}
}
자바입니다. 결과 >> 4000
int count8(int n) { if (n == 1) return 0; int cnt = 0, tmp = n; while (tmp > 0) { if (tmp%10 == 8) cnt++; tmp /= 10; } return count8(n-1) + cnt; }
int main() { printf("%d\n", count8(10000)); return 0; }
/*
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
*/
import java.util.*;
public class Algorithm1 {
public static Scanner sScan = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
String sInput = "";
int nMax = 0, nMin = 0, nMok = 0, nCount = 0;
sInput = sScan.nextLine();
nMin = Integer.parseInt(sInput.split(" ")[0]);
nMax = Integer.parseInt(sInput.split(" ")[2]);
for(int i = nMin; i <= nMax; i++) {
nMok = i;
while(nMok > 0) {
if(nMok % 10 == 8)
nCount++;
nMok = (int)(nMok / 10);
} // end while
} // end for
System.out.println(nMin + "부터 " + nMax + "까지의 8의 갯수는 : " + nCount + "개 입니다.");
}
}
c언어로 해봤습니다. . 정말 멋진 풀이들이 많이있네요 ! 제 짧은 경험으로는 이렇게 장황하게 나오네요 ㅠㅠ
#include<stdio.h>
int sNum[10];
void Count_Divide_Num(int a) { //이 함수는 하나의 수를 분해하여 개수를 출력함
int i, a_1, a_2, a_3, a_4, Num[10]; //a_ 변수들은 각각 1의자리 10의자리 100의자리 1000의 자리를 나타냄
for (i = 0; i <= 9; i++)Num[i] = 0;
//printf("%d를 분해하면...\n\n", a);
if (a < 10) {
a_1 = a;
}
else if (10 <= a&&a < 100) {
a_2 = a / 10;
a_1 = a - a_2 * 10;
}
else if (100 <= a&&a < 1000) {
a_3 = a / 100;
a_2 = (a - a_3 * 100) * 0.1;
a_1 = a - a_3 * 100 - a_2 * 10;
}
else if (1000 <= a&&a < 10000) {
a_4 = a / 1000;
a_3 = (a - a_4 * 1000) * 0.01;
a_2 = (a - a_4 * 1000 - a_3 * 100)*0.1;
a_1 = a - a_4 * 1000 - a_3 * 100 - a_2 * 10;
}
for (i = 0; i <= 9; i++) {
if (a_1 == i)Num[i] += 1;
if (a_2 == i)Num[i] += 1;
if (a_3 == i)Num[i] += 1;
if (a_4 == i)Num[i] += 1;
//printf("%d : %d개\n\n", i, Num[i]); //1부터 10000까지 반복하기 위해 주석처리
sNum[i] += Num[i];
}
}
int main() {
int i;
for (i = 0; i <= 9; i++)sNum[i] = 0;
for (i = 0; i <= 10000; i++)
Count_Divide_Num(i);
printf("1부터 10000까지 8의 개수는 : %d\n", sNum[7]);
}
//79COLUMNS////////////////////////////////////////////////////////////////////
// 구글 입사문제 중에서
#include <stdio.h>
#define NUM 8
#define TILL 10000
static int count(int n);
int main(void)
{
int rst = 0;
for (int n = 1; n <= TILL; n++)
rst += count(n);
printf("%d\n", rst);
return 0;
}
static int count(int n)
{
if (! n) return 0;
return ((n % 10 == NUM)? 1 : 0) + count(n / 10);
}
#include <stdio.h>
int main()
{
int i,j,k,l,m,eight;
i=j=k=l=m=eight=0;
for(i=0;i<1;i++)
{
for(j=0;j<10;j++)
{
for(k=0;k<10;k++)
{
for(l=0;l<10;l++)
{
for(m=0;m<10;m++)
{
if(m==8){eight=eight+1;}if(l==8){eight=eight+1;}if(k==8){eight=eight+1;}if(j==8){eight=eight+1;}
}
}
}
}
}
printf("8의 갯수는 %d입니다.\n",eight);
return 0;
}
C 로 무식하게 풀어봤습니다.
정답은 4000입니다.
public class Count8 { public static void main(String[] args) { int cnt = 0;
for (int i =0; i<=10000; i++){
String temp = String.valueOf(i);
for(int j =0; j<temp.length(); j++){
if(temp.charAt(j) == '8'){
cnt++;
}
}
}
System.out.println(cnt);
}
}
코딩 문제라기 보단 수학적 센스를 묻는 게 맞는 것 같네요 그래도 코딩사이트이니 코드도 짰습니다.
#include <iostream>
int main(void)
{
int sum = 0;
for(int i = 1; i <= 10000; i++)
{
int temp = i;
while(temp > 0)
{
if(temp % 10 == 8)
sum++;
temp /= 10;
}
}
std::cout << "Result: " << sum << std::endl;
}
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
var cnt int = 0
for i := 1; i <= 10000; i ++ {
cnt += strings.Count(strconv.Itoa(i), "8")
}
fmt.Println(cnt)
}
N = 10^K라 가정하고, S(K) = 1부터 10^K 까지의 8의 개수라고 가정하면,
S(0) = 0
S(i) = 10 * S(i-1) + 10^(i-1)
로 정리되므로, 다음과 같이 코드 작성하면 됩니다.
int solution(int N) {
int S = 0, K = 0, currentN = 1; // initial step, if K = 0
while (currentN < N) {
K++;
currentN *= 10;
S = 10 * S + (int)Math.pow(10, K-1); // S(K) = 10 * S(K - 1) + 10^(K-1), if K >= 1
}
return S;
}
Time Complexity : O(K)
단순히 loop돌면 Time Complexity : O(N * K)
public class cnt8 {
static int cnt = 0;
public static int cnt_8(int inputNum){
if(inputNum%10 == 8) cnt ++;
if(inputNum > 10) cnt_8(inputNum/10);
return cnt;
}
public static void main(String[] args) {
for(int i = 1; i<=10000; i++){
cnt_8(i);
}
System.out.println(cnt);
}
}
sum = 0
for number in range(1,80):
str_number = str(number)
str_len = len(str_number)
for digit in range(0, str_len):
if str_number[digit] == '8':
sum += 1
print sum
Scala
var count = 0
(1 to 10000).foreach(i => {
var f = i
while (f > 0) {
if (f % 10 == 8) {
count = count + 1
}
f = f / 10
}
})
println(count);
int result = 0;
for (int i = 1; i <= 10000; i++)
{
int temp = i;
while (temp != 0)
{
if(temp % 10 == 8)
{
result++;
}
temp /= 10;
}
}
Console.WriteLine($"result : {result}");
숫자 구하는 함수는 fn(숫자)라고 할 때 fn(1234) = fn(123) + fn(4) 라는 점을 이용합니다.
캐시에 매번 계산한 숫자를 저장하고 재사용하여 속도 향상을 노립니다. 캐시 히트율을 높이기 위해서 작은 숫자에서 큰 숫자로 계산을 해야합니다.
import java.util.HashMap;
import java.util.Map;
public class CountNumber {
public int count(int num, int target) {
return count(0, num, target);
}
private int count(int start, int end, int target) {
Map<Integer, Integer> cache = new HashMap<>();
int totalCount = 0;
for (int i = start; i <= end; i++) {
Integer cacheCount = cache.get(i / 10);
int count = (cacheCount == null ? 0 : cacheCount) + (i % 10 == target ? 1 : 0);
cache.put(i, count);
totalCount += count;
}
return totalCount;
}
}
#include <stdio.h>
int main()
{
int i = 0;
int j = 0;
int cnt = 0;
for (i = 1; i < 10000; i++)
{
j = i;
while (j)
{
if ((j%10!=0)&&(j%10)%8==0)
{
cnt = cnt++;
}
j = j / 10;
}
}
printf("%d",cnt);
}
결과 4000
public class Main {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 10000; i++) {
if (i % 10 == 8)
count++;
if (i % 100 / 10 == 8)
count++;
if (i % 1000 / 100 == 8)
count++;
if (i % 10000 / 1000 == 8)
count++;
}
System.out.println(count);
}
}
대단하십니다 다들. 윗분들 풀이보고 따라해봤네요.ㅠㅠ
static int cnt = 0;
public static void main(String[] args) {
for(int i=1; i<10001; i++) calc(i);
System.out.println(cnt);
}
public static int calc(int num){
if(num%10 == 8) cnt++;
if(num>10) calc(num/10);
return cnt;
}
''' How many '8' from 1 to 10,000? '''
import numpy as np
gen = (x for x in np.linspace(1,10000,10000))
sums = 0 for val in gen: sums += str(val).count('8')
print(sums)
숫자를 모두 문자열로 합친 후 정규표현식을 이용해 개수를 셌습니다
package kr.joao.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
for(int i=1;i<=10000;i++) {
sb.append(i + "");
}
Pattern pattern = Pattern.compile("8");
Matcher matcher = pattern.matcher(sb.toString());
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
}
[자바스크립트]
var i = 1;
var tmp = '';
var cnt = 0;
for(; i<=10000; i++) {
tmp = i + '';
for(var j=0; j<=tmp.length; j++){
if(tmp[j] == '8') {
cnt++;
}
}
}
console.log(cnt);
총 루프 수 : 48894
count = 0
for i in range(1, 10001):
num_list = list(str(i))
for n in num_list:
if n == "8":
count += 1
print(count)
def count8(n):
count = 0
n = str(n)
for i in n:
if i == '8':
count += 1
return count
x = [count8(i) for i in range(1,10000)]
print(sum(x))
n=10000
n8=0
for i in range(1,n+1):
for j in str(i):
if j=='8':
n8+=1
print(n8)
숫자를 문자로 바꿔서 쪼개고 더하기 했습니다. 처음 올려봐요~
public class Tester {
public static void main(String[] args) {
int count = 0;
for(int i = 1; i <= 10000; i++){
if(i/1000 == 8)
count++;
if((i%1000)/100 == 8)
count++;
if((i%100)/10 == 8)
count++;
if((i%10) == 8)
count++;
}
}
result = 0
def check(i):
for t in range(1,10) :
if i // 10 **t == 0 : return t
else : continue
for i in range(100) :
temp = i
for t in range(0,check(i)) :
if temp % 10 == 8 :
result += 1
# p.append()
temp = temp // 10
print(result)
public class Test4 {
public static void main(String[] args) {
int total = 0;
for (int i = 1; i <= 10000; i++) {
int num = i;
int cnt = 0;
String value = Integer.toString(num);
char[] chAr = value.toCharArray();
for (char ch : chAr) {
if (Character.getNumericValue(ch) == 8) {
cnt+=1;
}
}
total += cnt;
}
System.out.println(total);
}
}
li = []
for i in range(1,10001):
a = ''.join(str(i))
li.extend(a)
print(li.count(str(8)))
전형적인 입문자 수준 풀이
public static void main(String[] args) { int result = 0;
for(int x = 1; x <= 10000; x++) {
if(x % 10 == 8) result += 1;
if((x / 10) % 10 == 8) result += 1;
if((x / 100) % 10 == 8) result += 1;
if((x / 1000) % 10 == 8) result += 1;
}
System.out.println(result);
}
각 자리수별로 나눠서 카운팅했습니다.
static void Main(string[] args)
{
try
{
int count = 0;
char[] chArray = null;
for(int i = 0; i < 10000; i++)
{
chArray = i.ToString().ToCharArray();
foreach (var p in chArray)
{
if (p.Equals('8'))
{
count++;
}
}
}
Console.WriteLine(count);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadKey();
}
}
/**************************************************************************************************
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
***************************************************************************************************/
#include<stdio.h>
int Cnt_Eight(int input)
{
int result = 0;
if(input/1000==8)
{
result++;
input-=(input/1000)*1000;
}
else if(input>1000)
{
input-=(input/1000)*1000;
}
if(input/100==8)
{
result++;
input-=(input/100)*100;
}
else if(input>100)
{
input-=(input/100)*100;
}
if(input/10==8)
{
result++;
input-=(input/10)*10;
}
else if(input>10)
{
input-=(input/10)*10;
}
if(input/1==8)
{
result++;
}
return result;
}
int main(void)
{
int result=0,i;
for(i=1;i<10000;i++)
{
result += Cnt_Eight(i);
}
printf("%d",result);
return 0;
}
전 너무 어렵게 생각했나보네요...
func main(){
var totalCount = 0
for i in 1...10000{
var num = i
while num != 0 {
if ( num % 10 == 8 ){
totalCount += 1
}
num = num / 10
}
}
print(totalCount)
}
main()
앞에 멋진 풀이가 많지만... 단순하게 풀이했습니다.
public class searchEight{
public static void main(String args[]){
for(int i=0; i<=10000; i++){
searchEight(i);
}
System.out.println("1 ~ 10000 사이의 8 의 갯수 : " + count);
}
public static int count = 0; public static void searchEight(int num){ if((num % 10) == 8){ count++; } if(num > 10){ searchEight(num/10); } } }
파이썬 3.5.3
count = 0
for x in range(1,10000+1):
for y in str(x):
if y == '8':
count += 1
print(count)
int checkSum = 0; int totalSum = 0;
for(int i=1; i<=10000; i++) { checkSum = i.ToString().Split('8').Length - 1; if(checkSum > 0) totalSum += checkSum; }
Console.WriteLine(totalSum);
Print : 4000
def count8( n ):
num_list = []
for i in range( 1, n +1 ):
num_list.append( i)
str_list = str( num_list )
print( str_list.count( str(8) ))
count8( 10000 )
Python 3.6.0 입니다. 이중 for-loop 썼습니다. 답은 4000이라고 나오네요.
freq=0
for num_val in range (1,10000+1):
for char_val in str(num_val):
if int(char_val)==8:
freq+=1
print(freq)
어.. 원래 아마 코딩으로 풀라고 만든거 같은데 걍 코딩 없이 풀었습니당.
XXX8 인 경우에 1000개의 경우가 있고
XX8X 인 경우에도 1000개의 경우가 있고
X8XX 인 경우에도 1000개의 경우가 있고
8XXX 인 경우에도 1000개의 경우가 있으니깐 4 * 1000 해서 4000입니다.
Java 입니다.
public class Test {
public static void Excute(){
int count=0;
for(int i=1;i<10001;i++){
count+=counting8(i);
}
System.out.println("8갯수 : "+count);
}
public static int counting8(int n){
String strN = String.valueOf(n);
int c=0;
for(int i=0;i<strN.length();i++)if(strN.charAt(i)-48 == 8)c++;
return c;
}
public static void main(String[] args) {
Excute();
}
}
int sum = 0;
for(int i= 0;i<=10000;i++){
String aa = i+"";
sum += aa.length() - aa.replaceAll("8","").length();
}
System.out.println(sum);
using namespace std;
int main() { int num[10] = { 0 }; int ws, j;
for (int i = 1; i < 10001; i++)
{
for (ws = i;;)
{
num[ws % 10]++;
if (ws < 10) break;
ws /= 10;
}
}
cout << num[8];
}
연습하고 있어요 :)
min, max = 1, 10000
find_num = 8
count = 0
num = []
for i in range(min, max+1):
num = str(i)
for n in range(0, len(num)):
if int(num[n]) == 8 :
count += 1
num = []
print("count : %d" % count)
#include <iostream>
using namespace std;
const int lastIndex = 4;
void main()
{
int sum = 0;
int t = 1 / 10;
int count = 0;
for (int num = 1; num <= 10000; num++)
{
char strNum[6] = { 0, };
int idx = 0;
int tempNum = num;
while (1)
{
strNum[idx++] = (tempNum % 10) + '0';
tempNum = tempNum / 10;
if (tempNum == 0)
break;
}
for (int i = 0; i < 2; i++)
{
strNum[i] ^= strNum[lastIndex - i];
strNum[lastIndex - i] ^= strNum[i];
strNum[i] ^= strNum[lastIndex - i];
}
for (int i = 0; i < 5; i++)
{
if (strNum[i] == '8')
++count;
}
}
}
package training;
public class Count8 {
public static void main(String[] args) {
int iTotalSum = 0;
for(int i=0;i<10000;i++){
iTotalSum += count8(i);
}
System.out.println("FinalSum => "+iTotalSum);
}
public static int count8(int iNum) {
int iCnt = 0;
String strNum = String.valueOf(iNum);
for(int i=0;i<strNum.length();i++){
if("8".equals(strNum.substring(i, i+1))){
iCnt++;
}
}
return iCnt;
}
}
private static int countEight(int n){
int cnt = 0;
for(int i=1; i<=n; i++){
int num = i;
while(num > 0){
if(num % 10 == 8){
cnt++;
}
num = num / 10;
}
}
return cnt;
}
#풀이1
list=[]
for i in range(10):
for k in range(0,10):
for a in range(0,10):
for n in range(0,10):
list.append(i)
list.append(k)
list.append(a)
list.append(n)
print(list.count(8))
#풀이2
k=[]
for i in range(1,10001):
for a in str(i):
k.append(a)
print(k.count('8'))
제가 해놓고 다른분들 풀이 보니까 창피하네요..
/*
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
*/
import java.util.*;
class Count_8 {
public static void main(String[] args) {
System.out.print("숫자를 입력하세요 : ");
Scanner robot = new Scanner(System.in);
int num = robot.nextInt();
int cnt = 0;
for(int i = 1 ; i <= num ; i++){
int cnt_v = i;
while(true){
int temp = cnt_v%10;
if( temp%8 == 0 && temp!=0 ){
cnt++;
}
cnt_v /= 10;
if(cnt_v == 0){
break;
}
}
}
System.out.println("8의 개수! : "+cnt);
}
}
public class test2 {
public static void main(String[] args) {
int one;
int ten;
int hundred;
int thousand;
int count=0;
for(int i=1 ; i<=9999 ; i++)
{
if(i>=1 && i<10)
{
one = i;
if(one==8)
count++;
}
else if(i>=10 && i<100)
{
one = i%10;
ten = i/10;
if(one==8)
count++;
if(ten==8)
count++;
}
else if(i>=100 && i<1000)
{
one = i%10;
hundred = i/100;
ten = i/10 - hundred*10;
if(one==8)
count++;
if(ten==8)
count++;
if(hundred==8)
count++;
}
else if(i>=1000 && i<=9999)
{
one = i%10;
thousand = i/1000;
hundred = i/100-thousand*10;
ten = i/10-thousand*100-hundred*10;
if(one==8)
count++;
if(ten==8)
count++;
if(hundred==8)
count++;
if(thousand==8)
count++;
}
}
System.out.println(count);
}
}
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <math.h>
using namespace std;
int fun(int depth);
int mem[4][4];
int main()
{
memset(&mem[0][0], 0, sizeof(mem));
cout<<"result:"<<fun(0)<<endl;
return 0;
}
int fun(int depth)
{
int i,sum=0;
if(depth == 3)
return 1;
for(i=0;i<10;i++)
{
if(mem[i][depth] == 0)
{
mem[i][depth] += fun(depth+1);
if(i==8)
mem[i][depth] += pow(10, (3-depth)) ;
}
sum += mem[i][depth];
}
return sum;
}
int sum=0;
for(int i=1; i<=10000; i++){
if((i%10) == 8){sum+=1;}
if((i%100)/10 == 8){sum+=1;}
if((i%1000)/100 == 8){sum+=1;}
if(i/1000 == 8){sum+=1;}
}
print(sum);
답: 4000
public static void main(String[] args) {
String str = "";
for(int i = 1; i <= 10000; i++) {
if (String.valueOf(i).indexOf("8") != -1) {
str += String.valueOf(i);
}
}
int cnt = 0;
for(int j = 0; j < str.toString().length(); j++) {
if ('8' == str.charAt(j)) {
cnt++;
}
}
System.out.println(cnt);
}
public class Algorithm {
public static int resultNum(String str, int n){
int sum = 0;
for(int i=0; i<=n; i++){
if(str.charAt(i) == '8')
sum++;
}
return sum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int result = 0;
for(int i=1; i<10000; i++){
result += resultNum(String.valueOf(i),(int)Math.log10(i));
}
System.out.print(result);
}
}
count = 0
for index in range(1, 10001):
count += len([x for x in str(index) if x == '8'])
무식하게 풀었네요..
#include <iostream>
using namespace std;
int main()
{
int i, Headnum, Headnum2, Headnum3, count = 0;
i = 1;
for(;i < 10000; i++)
{
Headnum = (float)i / 10;
Headnum2 = (float)i / 100;
Headnum3 = (float)i / 1000;
if(Headnum3 == 8)
{
count += 1;
}
if(Headnum2 - Headnum3 * 10 == 8)
{
count += 1;
}
if(Headnum - Headnum2 * 10 == 8)
{
count += 1;
}
if(i - Headnum * 10 == 8)
{
count += 1;
}
printf("%d\n",count);
}
}
한줄... 허탈하네요...
string strNum;
int cnt = 0;
for (int i = 1; i <= 10000; i++)
{
strNum = i.ToString();
foreach (char a in strNum)
{
if (a == '8') cnt++;
}
}
JAVA
int cnt = 0;
for(int i = 1; i<=10000 ; i++){
String e = Integer.toString(i);
char[] cAr = e.toCharArray();
for(int wow = 0; wow<cAr.length ; wow++ ){
if(cAr[wow] == '8'){
cnt++;
}
}
}
System.out.println(cnt);
x = 1
y = []
n = 0
while n < 10000 :
if x < 10 :
x = str(x)
y.append(x[0])
elif 10 <= x < 100 :
x = str(x)
y.append(x[0])
y.append(x[1])
elif 100 <= x < 1000 :
x = str(x)
y.append(x[0])
y.append(x[1])
y.append(x[2])
elif 1000 <= x < 10000 :
x = str(x)
y.append(x[0])
y.append(x[1])
y.append(x[2])
y.append(x[3])
else :
x = str(x)
y.append(x[0])
y.append(x[1])
y.append(x[2])
y.append(x[3])
y.append(x[4])
x = int(x)
n = n + 1
x = x + 1
k = 1
l = 0
while k <= 10000 :
l = k + l
k = k + 1
m = 0
g = 0
while m < l :
if y[m] == 8 :
g = g + 1
print("1부터 10000까지 8이라는 숫자는 총 %d번 나온다" % g)
이러면 나올거 같긴 한데 실행시킨지 10분이 넘도록 제 컴퓨터가 연산해내지 못하는걸 보면 어마어마한 똥 프로그램인 듯 합니다!
적어놓고 다른 분들이 올리신거 보니까 반성하게 되네요... ㅠㅠ 뭐야 한줄은 엥엥
function countEight(n) {
count = 0;
for(var i = 1; i <= n; i++) {
var str8 = i.toString();
var matched8 = str8.match(/8/g);
matched8 ? count += matched8.length : null;
}
return count;
}
cnt = 0
for n in range(10001):
string=str(n)
for i in range(len(string)):
if string[i]=='8':
cnt+=1
print(cnt)
int count=0;
for(int i=1; i<10000; i++){
String leng=Integer.toString(i);
for(int j=0; j<leng.length(); j++){
int ex = Integer.parseInt(Character.toString(leng.charAt(j)));
if(ex==8){
count++;
}
}
}
System.out.println("count : "+count);
c로 풀이
#include <stdio.h>
int main(void)
{
int i,j,num=0;
for(i=1;i<=10000;i++) for(j=1;j<=1000;j*=10) if(((i/j)%10)==8) num++;
printf("%d\n",num);
}
엑셀 vba풀이
Dim sum as long
For i=1 to 10000
For s=1 to len(i)
If mid(i,s,1)=8 then:sum=sum+1
Next
Next
Msgbox sum & "번"
javascript(ES6)
// 1
var count = Array.from({length: 10000}, (v, k) => k + 1)
.join()
.split('')
.filter(n => n === "8")
.length;
console.log(count);
// 2
var count = Array.from({length: 10000}, (v, k) => k + 1)
.join()
.split("8")
.length - 1;
console.log(count);
let count = 0;
let num = 0;
let palFunc = () => {
for(let i = 1; i <= 1000; i++){
for(let j = 0; j < (i+'').length; j++){
num = ((i+'').charAt(j))*1;
if(num%8==0 && num != 0){
console.log(num);
count++;
}
}
}
return count;
}
console.log(palFunc());
def countnum(x):
count = str(x).count('8')
return(count)
total = 0
for i in range(0,10000):
total = total + countnum(i)
print (total)
public static void main(String[] args) {
int cnt=0;
for(int i=1;i<=9999;i++){
if(i%10==8)cnt++;
if((i/10)%10==8)cnt++;
if((i/100)%10==8)cnt++;
if((i/1000)%10==8)cnt++;
}
System.out.println(cnt);
}
#include<stdio.h>
int main(void)
{
int i;
int count=0;
for (i = 0;i <= 10000;i++) {
if (i / 10 == 0) {
if (i % 10 == 8)
count++;
}
else if (i / 100 == 0) {
if (i % 10 == 8)
count++;
if ((i / 10) % 10 == 8)
count++;
}
else if (i / 1000 == 0) {
if (i % 10 == 8)
count++;
if ((i / 10) % 10 == 8)
count++;
if (((i / 10) / 10) % 10 == 8)
count++;
}
else {
if (i % 10 == 8)
count++;
if ((i / 10) % 10 == 8)
count++;
if (((i / 10) / 10) % 10 == 8)
count++;
if ((((i / 10) / 10) / 10) % 10 == 8)
count++;
}
}
printf("%d", count);
}
파이썬으로 작성 하였습니다.
count = 0
for i in range(1,10001):
for j in str(i):
if int(j) == 8:
count +=1
print(count)
value=0
for member in range(10001):
num = list(str(member))
num_eight = num.count('8')
value = value + num_eight
print(value)
public class numbersOfEight
{
public static void main(String[] args)
{
int result = 0;
for(int i = 0; i <= 10000; i++)
{
int temp = i;
while(temp > 0)
{
if(temp % 10 == 8)
result ++;
temp = temp / 10;
}
}
System.out.println(result);
}
}
간단한 정규식을 이용해서 풀어봤습니다.
import re
total = 0
p = re.compile('8')
for i in range(10000):
t = str(i)
if '8' in t:
total += len(p.findall(t))
print total
public class Ex003 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sumOfEight=0;
for(int i=1; i<=10000; i++) {
int temp = i;
do {
if(temp%10 == 8)
sumOfEight++;
temp /= 10;
}while(temp != 0);
}
System.out.println("8숫자의 총합: " + sumOfEight);
}
}
앞에 좋은 풀이가 많았지만 그래도 연습차원에서 Python으로 풀어봤습니다.
print(len([d for x in range(1, 10001) for d in str(x) if d is '8']))
적고 보니, 아래가 더 간단하게 보이네요.
print(sum(str(x).count('8') for x in range(1, 10001)))
def count8(ub):
cnt = 0
for i in range(1, ub+1):
cnt += str(i).count('8')
return cnt
# ub = 10^x, x>=2 라고 가정
# count8_rec(1000) = 8xx 100개 + count8_rec(100) * 10개
def count8_rec(ub):
if ub is 10: return 1
return ub // 10 + 10 * count8_rec(ub // 10)
print(count8(10000), count8_rec(10000))
두가지 다 해 봤습니다. 오.. 다른 풀이를 보니 위에 건 한 줄로 되는군요. 아직 익숙하질 않음
sum = 0 for I in range(1, 10001): num = 0 a_str = str(i) a_list = list(a_atr) for count in range(0, Len(a_str)): if a_list[count] == '8': num = num + 1 sum = sum + num print(num)
def count8(num):
count = 0
for i in str(num):
if i == '8':
count += 1
return count
answer = 0
for j in range(1,10001):
answer += count8(j)
print(answer)
package java_tutorial;
public class Count8 {
public static void main(String[] args) {
int count = 0;
for(int i = 1; i < 10000; i++)
{
if(i/1000==8) {count++;}
if((i/100)%10==8) {count++;}
if((i/10)%10==8) {count++;}
if(i%10==8) {count++;}
}
System.out.println("The Answer is " + count++);
}
}
#include <stdio.h>
#include <string.h>
#define _CRT_SECURE_NO_WARNNINGS
#define MAX 39000
int total();
int main()
{
int res;
res = total();
printf("Total : %d\n", res);
return 0;
}
int total()
{
char string[MAX] = { 0 };
char tmp[6];
int i, res=0;
for (i = 1; i <= 10000; i++) {
sprintf(tmp, "%d", i);
strcat(string, tmp);
}
for (i = 0; i < strlen(string); i++)
if (string[i] == '8')
res++;
return res;
}
#include<stdio.h>
int main(void)
{
int i;
int cnt = 0;
for (i = 1; i <= 10000; i++)
{
if (i % 10 == 8)
cnt += 1;
if ((i / 10)%10 == 8)
cnt += 1;
if ((i / 100)%10 == 8)
cnt += 1;
if (i / 1000 == 8)
cnt += 1;
}
printf("%d\n", cnt);
return 0;
}
#include <stdio.h>
#define START 1
#define END 10000
int result;
void FindEightToAdd(int); //8의 개수 더하기
int main()
{
int i;
//8의 개수 총합
for (i = START; i <= END; i++)
{
FindEightToAdd(i);
}
printf("%d\n", result);
return 0;
}
void FindEightToAdd(int input)
{
if (input % 10 == 8)
{
result++;
}
if (input > 0)
{
FindEightToAdd(input / 10);
}
}
public class Count8 {
public static void main(String[] args) {
int cnt=0;
for(int i=0; i<10000; i++)
cnt += eightCount(i,0);
System.out.println(cnt);
}
public static int eightCount(int n, int cnt) {
if(n%10 == 8) cnt++;
if(n/10 > 0) return eightCount(n/10,cnt);
return cnt;
}
}
import java.util.Arrays;
import java.util.stream.IntStream;
public class Lv2 {
public void func(int num) {
int count = 0;
char[] arr = Arrays.toString(IntStream.range(1, num+1).toArray()).toCharArray();
for (char c : arr) if (c == '8') count++;
System.out.println(count);
}
public static void main(String[] args) {
Lv2 obj = new Lv2();
obj.func(10000);
}
}
int cnt = 0;
for (int i = 1; i <= 10000; i++) {
char[] c = Integer.toString(i).toCharArray();
int len = c.length;
for (int j = 0; j < len; j++) {
if (c[j] == '8') {
cnt++;
}
}
}
System.out.println(cnt);
sum = 0
for n in range(1,10001):
b = [int(i) for i in str(n)]
for num in b:
if num ==8:
sum += 1
print(sum)
public class Calculate {
public static void main(String[] args) {
int maxNum = 10000;
int cnt = 0;
String tmp = "";
for (int i=1 ; i<=maxNum ; i++) {
tmp = i+"";
cnt += tmp.length()-tmp.replaceAll("8", "").length();
}
System.out.println("cnt : "+cnt);
}
}
public static void getNumberCnt() {
int splitLength = 0;
for(int i=1; i<=10000; i++) {
splitLength += String.valueOf(i).split("8",-1).length -1;
}
System.out.println(splitLength);
}
public static void main(String[] args) {
getNumberCnt();
}
답은 4000
sum = 0
for i in range(1, 10001):
sum += str(i).count('8')
print(sum)
4000
숫자를 문자열로 바꾼뒤 개수를 세서 합했습니다.
import string
eight_count=0
for i in range(1,10001):
i=str(i)
temp_count=i.count('8')
eight_count+=temp_count
print(eight_count)
풀고 나서 보니 이미 있네요.. 죄송합니다. (푼거 안보이게 할수 없나요 나만 보게 ㅜㅜ)
print(''.join(list([str(x) for x in range(1,10001)])).count('8'))
public class Main {
public static void main(String[] args) {
int cnt = 0;
for (int i=1; i<=10000; i++) {
if (i/1000%10 == 8) cnt++;
if (i/100%10 == 8) cnt++;
if (i/10%10 == 8) cnt++;
if (i%10 == 8) cnt++;
}
System.out.println(cnt + "번");
}
}
result = 0
for i in range(1,10001):
trans_str = str(i)
for j in trans_str:
if(int(j) == 8): result+=1
print(result)
public class Example7 {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10000; i++) {
sum += GetCounter(String.valueOf(i));
}
System.out.println(sum);
}
private static int GetCounter(String s) {
int counter = 0;
for (Character c : s.toCharArray()) {
if (c.equals('8')) {
counter++;
}
}
return counter;
}
}
뭔가 람다로 간단하게 할 수 있는 방법이 있을것 같은데... 모르겠네요
// CD007 - 구글 입사문제 중에서
package main
import (
"fmt"
"strings"
)
func main() {
count := 0
for i := 1; i <= 10000; i++ {
count += count8(fmt.Sprint(i))
}
fmt.Println(count)
}
// count "8"s in aString
func count8(aString string) int {
count := strings.Count(aString, "8")
return count
}
public class Ex3 {
public static int cnt;
public static void main(String[] args) {
for(int i=1;i<10000;i++) {
count(i);
}
System.out.println(cnt);
}
public static void count(int number) {
int[] no = new int[4];
no[0] = number/1000;
no[1] = (number%1000)/100;
no[2] = (number%100)/10;
no[3] = (number%10);
for(int i=0;i<no.length;i++) {
if(no[i] == 8) {
cnt++;
}
}
}
}
문제를 좀더 응용해서 사용자가 입력한 숫자에서 8을 카운팅 하는것으로 풀었습니다.
package org.Solve_3_keyboard_scan;
import java.util.Scanner;
import java.util.ArrayList;
public class Solve_3_keyborad_scan { public static void main(String[] args){
Number test1 = new Number();
test1.main();
test1.Collection_8();
test1.Count_8();
System.out.println(test1.result);
// for (int p =0 ; p<test1.collection_number.size();p++){ // System.out.println(test1.collection_number.get(p)); // } }
} class Number { ArrayList number = new ArrayList(); ArrayList collection_number = new ArrayList(); int limit; int result;
public void main() {
System.out.println("자연수를 입력해주세요 : ");
Scanner sc = new Scanner(System.in);
limit = sc.nextInt();
for (int t = 0; t < limit + 1; t++) {
number.add(t);
}
}
public void Collection_8() {
for (int origin_N = 1; origin_N < number.size(); origin_N++) {
String length1 = String.valueOf((int) number.get(origin_N));
int length2 = length1.length();
if (length2 == 1) {
String collection_1 = length1.substring(0);
collection_number.add(collection_1);
} else {
for (int where = 0; where < length2; where++) {
String collection_2 = length1.substring(where, where + 1);
collection_number.add(collection_2);
}
}
}
}
public void Count_8() {
for (int Count = 0; Count < collection_number.size(); Count++) {
if (Integer.parseInt((String)collection_number.get(Count))== 8) {
result = result + 1;
} else {
}
}
}
}
파이썬 3.6버전입니다.
num_list에 1~10000까지 각 숫자에 들어간 8의 개수를 list로 넣어서 sum함수로 더했습니다.
num_list=[]
for num in range(1,10001):
num_str=str(num)
num_list.append(num_str.count('8'))
print(sum(num_list))
#include <iostream>
#include <vector>
#include <stack>
#include <math.h>
using namespace std;
int check_digit(int num) {
int count = 0;
while (1) {
count++;
if (num < pow(10, count))
return count;
}
}
int pick_num(int num, int digit) {
int num1 = pow(10, digit);
int num2 = pow(10, digit - 1);
int result = (num%num1 - num%num2)/pow(10,digit-1);
return result;
}
int count_8(int num) {
int digit = check_digit(num);
int count = 0;
for (int i = 1; i <= digit; i++) {
if (pick_num(num, i) == 8)
count++;
}
return count;
}
int main() {
int num = 10;
cout << "Type number" << endl;
cin >> num;
int sum = 0;
for (int i = 0; i <= num; i++) {
sum += count_8(i) * 8;
}
cout << sum << endl;
}
class count():
def counts(self): counteight = 0 for num in range(1,100): num = list(str(num)) for number in num: if number == '8': counteight = counteight + 1
return counteight
a = count() b = a.counts() print(b)
package codingdojang;
public class ex7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count = 0;
for(int i=0; i < 10001; i++) {
if((i/1000)%10 == 8) count++;
if((i/100)%10 == 8) count++;
if((i/10)%10 == 8) count++;
if((i/1)%10 == 8) count++;
}
System.out.println(count);
}
}
def count_8(number):
s = str(number)
count = 0
for n in range(len(s)):
if 8 == int(s[n]): count += 1
return count
total = 0
for n in range(10000):
total += count_8(n)
단순 사칙 연산으로 풀었습니다만, 계산 과정에서 각 자릿수로 나눈 나머지에서 다시 나눠서 구했습니다. 먼저 각 자릿수로 나누고나서 나머지로 구하는 식도 있던데 서로 정답을 구할 순 있었습니다. 어떤게 더 나은지는 잘 모르겠네요..
public class googleMatter {
public static void main(String[] args) {
int count = 0;
for(int number = 1; number < 10000; number ++) {
if( number / 1000 == 8 ) {
count ++;
}
if( (number % 1000) / 100 == 8 ) {
count ++;
}
if( (number % 100) / 10 == 8 ) {
count ++;
}
if( number % 10 == 8 ) {
count ++;
}
}
System.out.println("Result : " +count);
}
}
function solve() {
let count = 0;
for(let i = 8; i <= 10000; i+=10){
let n = i;
do {
if(n%10 === 8){
count++;
}
n = Math.floor(n/10);
} while(n > 1);
}
return count;
}
console.log(solve());
package 구글문제;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
/*
* 1~10000까지의 서 8이라는 숫자는 몇게 나오냐
*/
public class GoogleProblem {
public static void main(String[] args)throws IOException {
int HowEight=0;
String getStr;
System.out.println("숫자를 입력주세요 : ");
int input = new Scanner(System.in).nextInt();
FileOutputStream fos = new FileOutputStream("Log.txt");
for(int i=1; i<input; i++) {
getStr = i+"";
if(getStr.contains("8")) {
String sub [] = new String[getStr.length()];
for(int j=0; j<sub.length; j++) {
sub[j] = getStr.substring(j, j+1);
}//for
String buf = Arrays.toString(sub)+"\n";
fos.write(buf.getBytes());
System.out.println(Arrays.toString(sub));
for(int k=0; k<sub.length; k++) {
if(sub[k].equals("8"))
++HowEight;
else
continue;
}
}
}
System.out.println("total : "+HowEight);
}
}
def counting(n, m):
nist = []
nist = list(str(n))
count = 0
for i in nist:
if i == str(m):
count = count + 1
return count
count = 0
for i in range(1, 10001):
count = count + counting(i, 8)
print (count)
#include <stdio.h>
int main()
{
int m = 0;
int o = 0;
int s = 0;
for(int i = 0; i < 10000; i++)
{
o = i;
while(o > 0)
{
m = o % 10;
o = o / 10;
if(m == 8)
{
s++;
}
}
}
printf("%d\n", s);
}
간단한 해법도 존재하군요
int count = 0;
for (int i = 0; i <= 10000; i++)
{
int temp = i;
while (temp)
{
if (temp % 10 == 8) count++;
temp /= 10;
}
}
cout << "총 갯수 : " << count << endl;
alist = []
for i in range(1,10001):
for j in list(str(i)):
if '8' in j:
alist.append(j)
alist.count('8')
저는 숫자를 각 자리로 쪼개서 리스트로 만들고, 그 안에 8이 있으면 모두 alist에 삽입하는 형식으로 alist를 만들었습니다. 그리고 그 리스트에서 8을 세었습니다. 언어는 파이썬입니다.
public class CountEight {
public static void main(String[] args) {
int cnt = 0;
for(int i = 1; i <= 10000; i++){
if(i%10 == 8) cnt++;
if((i/10)%10 == 8) cnt++;
if((i/100)%10 == 8) cnt++;
if((i/1000)%10 == 8) cnt++;
}
System.out.println(cnt);
}
}
# 한글 처리 in Atom 1.21.1 + Anaconda(Python 3.6.3) on Mac
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')
# 1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
# 8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
# (※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
print(''.join(str(i) for i in range(1, 10001)).count('8'))
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace numberCounting
{
class Program
{
static void Main(string[] args)
{
const int NUM = 8;
int divideNum = 1;
int count = 0;
//각 자릿수에서 8이면 count를 올림
for(int i = 1; i <= 10000; i++)
{
while(i / divideNum >= 1)
{
int temp;
temp = (i % (divideNum * 10)) / divideNum;
//Console.WriteLine(i + " " + temp);
if (temp == 8)
{
count++;
}
divideNum *= 10;
}
divideNum = 1;
}
Console.WriteLine(count);
}
}
}
public static int countStr(String str){ String[] arr = str.split("8"); int result = arr.length -1; return result; }
public class Main {
static int chk(int n) {
int ret = 0;
while (n != 0) {
if (n % 10 == 8) {
ret++;
}
n /= 10;
}
return ret;
}
public static void main(String[] args) {
int rst = 0;
for (int i = 1; i <= 10000; i++) {
rst += chk(i);
}
System.out.println(rst);
}
}
class Program
{
static void Main(string[] args)
{
int count = 0;
for(int i = 1; i <= 10000; i++)
{
string number = i.ToString();
for(int j = 0; j < number.Length; j++)
{
if(number[j] == '8')
{
count++;
}
}
}
Console.WriteLine(count);
}
}
def getEightDigitCount(num):
numStr = str(num)
result = 0;
for digit in numStr:
if digit == "8":
result = result + 1
return result
MAX_NUM = 1000
for i in range(1, MAX_NUM):
print(str(i) + "," + str(getEightDigitCount(i)))
newList = [getEightDigitCount(i) for i in range(1, MAX_NUM)]
print(sum(newList))
#define MAX 10000
int main()
{
int i;
int a;
int k;
int c=0;
for (i = 1; i <= MAX; i++)
{
a = i;
while (a > 0)
{
k = a % 10;
if (k == 8)
c++;
a /= 10;
}
}
printf("%d", c);
}
(loop for n from 1 to 10000 sum ((lambda (num) (count #\8 (prin1-to-string num))) n))
4000
const countEight = num => {
return Array.from(new Array(num), (_, i) => i + 1).join().match(/8/g).length;
};
console.log(countEight(10000));
cnt = 0
for num in range(10000):
while num != 0:
if num%10==8:
cnt += 1
if num>10: num = num/10
else: break
print cnt
문자열로 처리하는 게 10씩 나눠서 처리하는 것보다 빠르다니 ..
public class Google { private static int count = 0; public static void main(String args[]){ for(int num = 1 ; num <= 10000; num++){ String numStr = String.valueOf(num); int sl = numStr.length(); for (int i=0; i < sl; i++){ if ( numStr.charAt(i) == '8') count++; } } System.out.println("count is "+count); } }
count = 0
for i in range(1,10000):
goo = str(i)
for a in range(len(goo)):
if(goo[a] == '8'):
count+=1
print(count)
NumCnt = 0;
for x in range(10000):
for idx in range(0, len(str(x))):
if (str(x))[idx] == "8":
NumCnt = NumCnt + 1
print(str(NumCnt))
#1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
#8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
#(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
# count = 0
# the_eight = "8"
# for eight in range(1,10000):
# if the_eight in str(eight):
# length_eight = len(str(eight))
# for x in range(length_eight):
# if str(eight)[x] == the_eight:
# count += 1
# print (eight, count)
# else:
# pass
# else:
# pass
#
# print (count)
#참고하여 쓴 답
print ((str(list(range(1,10000)))).count('8'))
def eight(x):
return x == "8"
num8=0
for i in range(1,10001):
number = str(i)
a = list(number)
num8=num8+len(filter(eight,a))
print num8
import re
int_n = list(range(1,10001))
int_str = str(int_n)
k = re.findall("8", int_str)
print(len(k))
package programming;
public class oiler {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 10000; i++) {
if ((i % 10) == 8)
count++;
if (((i / 10) % 10) == 8)
count++;
if (((i / 100) % 10) == 8)
count++;
if ((i / 1000) == 8)
count++;
}
System.out.println(count);
}
}
count = 0
for i in range(1,10001):
for x in str(i):
if x == "8":
count += 1
print(count)
#고수분들 한줄 코딩 리스펙트합니다! 저는 아직 초보라 이렇게 풀어써야하는데말이죠 ㅎㅎ
public class howManyTimes8 {
// 숫자 n에 대하여 8이 몇개 들어있는지 알 수 있음
public static int catch8(int input) {
String num = ""+input+"";
int size = num.length();
char[] arr = new char[size];
for(int i=0; i<size; i++) {
arr[i] = num.charAt(i);
}
// ㄴㅡㅡ input값의 각 자리수가 들어간 배열 arr 생성
int count=0;
for(int i=0; i<size; i++) {
if(arr[i] == '8')
count++;
}
return count;
}
// 1부터 n까지 catch8() 실행
public static int count8(int n) {
int result=0;
for(int i=1; i<=n; i++) {
result = result + catch8(i);
}
System.out.println(result);
return result;
}
public static void main(String[] args) {
count8(100);
}
}
파이썬 3.6
count = 0
for i in range(1,10001):
if '8' in str(i):
count += str(i).count('8')
print(count)
4000
파이썬 입니다.
cnt=0
for i in range(1,10001):
for j in range(len(str(i))):
if str(i)[j]=='8':
cnt=cnt+1
print(cnt)
final static int MAX = 10000;
static int cnt = 0;
public static void main(String[] args) {
main m = new main();
for(int i = 0; i < MAX; i++)
{
m.counting_eight(i+1);
}
System.out.println(cnt);
}
public void counting_eight(int num) {
if (num % 10 == 8)
cnt++;
if (num > 10)
counting_eight(num / 10);
}
자바요... 허허허....
public class Example { public static void main(String[] args) { int sum=0; for(int i=1; i<=10000; ++i) { String temp = String.valueOf(i); for(int j=0; j<temp.length(); ++j) if(temp.charAt(j) == '8') ++sum; }
System.out.println(sum);
}
}
public class Example
{
public static void main(String[] args)
{
int sum=0;
for(int i=1; i<=10000; ++i)
{
String temp = String.valueOf(i);
for(int j=0; j<temp.length(); ++j)
if(temp.charAt(j) == '8')
++sum;
}
System.out.println(sum);
}
}
자바
int count = 0;
for(int i = 0; i < 10000; i++) {
String ans = String.valueOf(i);
for(int j = 0; j < ans.length(); j++) {
if(ans.charAt(j) == '8') count += 1;
}
}
System.out.println(count);
public static void main(String[] args) {
int count = 0; // 8의 개수.
for(int i = 1; i <= 10000; i++)
{
int n = i; // i 값을 n에 대입.
while(n > 0)
{
if(n % 10 == 8) // 각 자리 숫자를 10으로 나눠서 8이 나오면 count++.
count++;
n = n / 10; // n을 한자리 줄여줌.
}
}
System.out.println(count);
}
답이 4000이 나왔는데 맞나요??
tot=0
for i in range(10001):
i = str(i)
a = list(i)
for j in range(len(a)):
if int(a[j])==8:
tot += 1
print(tot)
google<-function(x,y,n){
count <- 0
for(i in x:y){
tmp <- unlist(strsplit(as.character(i),split=character(0)))
for(j in 1:NROW(tmp)){
if(tmp[j]==n){ count <- count+1 }
}
}
print(count)
}
r로 풀었습니다.
a<-0
for(i in 1:10000){
if(i%%10==8){
a<-a+1}
if((i%/%10)%%10==8){
a<-a+1}
if((i%/%100)%%10==8){
a<-a+1}
if((i%/%1000)%%10==8){
a<-a+1}
}
print(a)
``````{.r}
count = 0
for i in range(10000):
if i//1000 == 8:
count += 1
if i//100%10 == 8:
count += 1
if i//10%10 == 8:
count += 1
if i%10 == 8:
count += 1
print(count)
package countingEight;
import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;
public class CountingEight {
private int getEight(int n) {
int count = 0;
for (int i = 0; i < n; i++) {
String str = Integer.toString(i);
for (int j = 0; j < str.length(); j++)
if (str.substring(j, j + 1).contains("8"))
count++;
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CountingEight ce = new CountingEight();
System.out.println(ce.getEight(10000));
}
}
<script>
function _count(c) {
var i = String(c);
var _sum = 0;
for (j = 0; j < i.length; j++){
if ( "8" == i[j] ) {
_sum = _sum +1;
};
};
return _sum;
}
var _sum_overall = 0
for (i = 0; i < 10001; i++) {
_sum_overall = _sum_overall + _count(i);
}
console.log(_sum_overall)
</script>
다들 어마 무시 하세요;;
list=[]
count=0
for i in range(10000):
list.append('%d' %(i+1))
for i in range(len(list)):
for j in range(len(list[i])):
if list[i][j]=='8':
count+=1
else:
continue
print count
그냥 4천개 혹은
# 파이썬
result = 0
for t in range(1, 10001):
for u in str(t):
if u == '8':
result += 1
print(result)
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner scanf=new Scanner(System.in);
int a=scanf.nextInt();
String s="";
int cnt=0;
for(int i=1; i<=a; i++) {
s=i+"";
for(int j=0; j<s.length(); j++) {
if((s.charAt(j)+"").equals("8")) {
cnt=cnt+1;
}
}
}
System.out.println(cnt);
}
}
n = int(input("범위를 입력하시오: "))
result = 0
for i in range(1,n+1):
a = list(str(i))
for j in range(len(a)):
if a[j] == '8':
result += 1
print(result)
total = 0
def test(num):
cnt = 0
for c in str(num):
if int(c) == 8:
cnt += 1
return cnt
for i in range(1, 10000):
total += test(i)
print(total)
#include <iostream>
#define SIZE 10000
using namespace std;
void save(int* arr,int num);
int main()
{
int arr[4] = {0};
int sum = 0;
for(int i=1;i<SIZE;i++)
{
save(arr,i);
for(int j=0;j<4;j++)
{
if(arr[j] == 8) sum++;
}
}
cout << "8의 개수 :" << sum << endl;
return 0;
}
void save(int* arr,int num)
{
int j=1000;
for(int i=3;i>=0;i--)
{
arr[i] = num/j;
num%=j;
j/=10;
}
}
int main(){ int i=1; int cnt=0; int num; while(i<10000){ // 범위 내 8 카운트 // 자릿수 분리 num=i; while(num!=0){ if(num%10==8) cnt++; num/=10; } i++; } printf("%d",cnt); }```{.cpp}
```
def eight():
n=input('range:')
a=range(1,n+1)
temp=[]
for i in a:
for j in (str(i)):
temp.append(j)
print temp.count('8')
answer:4000
def count8(n):
count = 0
for i in range(1,n+1):
if '8' in str(i):
count += sum(str(i)[j] == '8' for j in range(0,len(str(i))))
return count
count8(10000)
public class eightSum {
final private int number = 8;
private int sum = 0;
public int SumEight() {
for(int i = 1; i <= 10000; i++) {
String str = i + "";
for(int j = 0; j < str.length(); j++) {
if(Integer.parseInt(str.charAt(j)+"") == number) {
sum++;
}
}
}
return sum;
}
}
자바입니다!
package CodingDojang;
import java.util.*;
public class CountEight {
static final int MAX = 10000;
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
String All = "";
String[] splitedAll;
int numOfEight;
for(int i = 1; i <= MAX; i++) {
All += i;
}
splitedAll = All.split("8");
numOfEight = splitedAll.length - 1; //문자열 변수 All에서 맨 앞 문자와 맨 뒤 문자가 '8'이 아닌경우에만 사용 가능, 문제
에서 맨 앞 문자는 1, 맨뒤 문자는 10000의 0
System.out.println(numOfEight);
scn.close();
}
}
public class Cnt8 {
public static void main(String[] args) {
int cnt = 0;
int a,b,c,d;
for (int i = 1; i < 10000; i++) {
a = i/1000;
b = (i%1000)/100;
c = ((i%1000)%100)/10;
d = ((i%1000)%100)%10;
if (a == 8)
cnt++;
if (b == 8)
cnt++;
if (c == 8)
cnt++;
if (d == 8)
cnt++;
}
System.out.println("Answer is " + cnt);
}
}
public class Counting {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count = 0;
for(int i=1; i<=10000 ;i++ ){
Integer number = new Integer(i);
String numberString = number.toString();
int n= 0;
while(n < numberString.length()){
char c = numberString.charAt(n);
if(c == '8'){
count++;
}
n++;
}
}
System.out.println(count);
}
}
4000
print(len(list(int(x) for numbers in range(1, 10000) for x in str(numbers) if int(x) == 8)))
Python 3이고요 최근에 배운 list comprehension을 사용했습니다
Swift로 해봤습니다. 백만까지 높여서 테스트를 해보니, 역시 문자열 변환없는 첫번째 방식이 압도적으로 빠르네요.
import Foundation
let maxNumber = 1000000
let sw1 = DispatchTime.now()
// -----------------------------------
// Implementation 1 - String 변환 없음
// -----------------------------------
var count1 = 0
for i in 1...maxNumber {
var number = i
while(number > 0) {
if number % 10 == 8 {
count1 += 1
}
number /= 10
}
}
print (count1)
let sw2 = DispatchTime.now()
// -----------------------------------
// Implementation 2 - String으로 변환
// -----------------------------------
var count2 = 0
for i in 1...maxNumber {
let numberString = String(i)
for letter in numberString {
if letter == "8" {
count2 += 1
}
}
}
print(count2)
let sw3 = DispatchTime.now()
// -----------------------------------
// Implementation 3 - String으로 변환 - Variation 1
// -----------------------------------
var count3 = 0
for i in 1...maxNumber {
let numberString = String(i)
count3 += String(numberString.filter {$0 == "8"}).count
}
print(count3)
let sw4 = DispatchTime.now()
// -----------------------------------
// Implementation 4 - String으로 변환 - Variation 2
// -----------------------------------
var count4 = 0
for i in 1...maxNumber {
let numberString = String(i)
_ = numberString.filter {if $0 == "8" {count4 += 1}; return $0 == "8"}
}
print(count4)
let sw5 = DispatchTime.now()
let elappsed1 = Double(sw2.uptimeNanoseconds - sw1.uptimeNanoseconds) / 1_000_000_000
print ("Elappsed 1 : \(elappsed1) seconds")
let elappsed2 = Double(sw3.uptimeNanoseconds - sw2.uptimeNanoseconds) / 1_000_000_000
print ("Elappsed 2 : \(elappsed2) seconds")
let elappsed3 = Double(sw4.uptimeNanoseconds - sw3.uptimeNanoseconds) / 1_000_000_000
print ("Elappsed 3 : \(elappsed3) seconds")
let elappsed4 = Double(sw5.uptimeNanoseconds - sw4.uptimeNanoseconds) / 1_000_000_000
print ("Elappsed 4 : \(elappsed4) seconds")
1 #include <stdio.h>
2
3 int main(void) {
4
5 int dx;
6 int att;
7 int a, b, c, d, e;
8 for (int dx = 0; dx < 10000; ++dx) {
9
10 a = dx/10000;
11 b = dx/1000 - a*10;
12 c = dx/100 - a*100 - b*10;
13 d = dx/10 - a*1000 - b*100 - c*10;
14 e = dx - a *10000 - b*1000 - c*100 - d*10;
15 switch (a)
16 case 8 :
17 att++;
18 switch (b)
19 case 8 :
20 att++;
21 switch (c)
22 case 8 :
23 att++;
24 switch (d)
25 case 8 :
26 att++;
27 switch (e)
28 case 8 :
29 att++;
30
31 }
32
33 printf("%d", att);
34
35 return 0;
36 }
c언어 너무 어려워요..ㅠㅠㅠㅠㅠ
python 3.6.1
count = 0
for num in range(1, 10001):
for i in range(0, len(str(num))):
if str(num)[i] == '8':
count += 1
print(count)
public class Goo{
public static void main(String[] args){
int i,j;
int total1 = 0;
for(i=0;i<10000;i++){
int num1 = (i+1);
String input1 = Integer.toString(i+1);
int n = input1.length();
for(j=0;j<n;j++){
if(num1 % 10 == 8)
total1 +=1;
else;
num1 = num1/10;
}
}
System.out.print("8은 총 " + total1 + "개입니다.");
}
}
JAVA 입니다
``````{.java} public static void checkNumber() { int count = 0; int chkNum = 0; int mok = 0;
for(int i = 0; i < 10000; i++) {
mok = i;
while(mok != 0) {
chkNum = mok % 10;
mok = mok / 10;
if(chkNuM == 8) {
count++;
}
}
}
System.out.println("checkEightCount : " + count);
} ```
public static int numCountCheck(String num){
String check=num;
int count=0;
for(int i=1; i<=10000; i++){
check = i+"";
for(int j=0; j<check.length(); j++){
if(j+1<=check.length()){
if(check.substring(j, j+1).equals(num)){
count++;
}
}
}
}
return count;
}
public class Test {
private int cnt;
public Test(){
cnt=0;
}
public void countEight(String input) {
for(int i=0; i<input.length(); i++){
if(input.charAt(i)=='8') cnt++;
}
}
public static void main(String[] args) {
Test test = new Test();
for(int i=1; i<=10000; i++){
test.countEight(Integer.toString(i));
}
System.out.println(test.cnt);
}
}
public class loop2
{
public static void main(String[] args)
{
int a = 0;
StringBuilder s = new StringBuilder();
for(int i = 1; i <= 10000; i++){
s.append(i);
}
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == '8')
a++;
}
System.out.println(cnt);
}
}
"""
author: Kenny Jeon
date: 04/09/2018
"""
def func():
cnt = 0
# declare 8 count variable
for num in range(1, 10001, 1):
digits = str(num)
# convert num to string
for digit in digits:
if int(digit) == 8:
cnt += 1
# check 8 digit in digits
return cnt
if __name__ == "__main__":
result = func()
print(result)
def eight():
count = 0
i=1
while i < 10001:
a = str(i)
for j in range(0, len(a)):
if a[j] == '8':
count+=1
i+=1
return count
print(eight())
#include<iostream>
using namespace std;
int solution()
{
int num = 1;
int remain = 0, reauq, sum = 0;
int count = 0;
while (num != 10000)
{
reauq = num;
num++;
while (reauq != 0)
{
remain = reauq % 10;
reauq /= 10;
if (remain == 8)
count++;
}
}
return count;
}
int main()
{
cout << solution() << endl;
}
그외에 정규표현식으로 해결이 가능할 듯 합니다만..
import java.util.stream.IntStream;
/**
* @author Kimseongsu
* @see http://codingdojang.com/scode/393
*/
public class Problem393 {
static final int MAX = 10000;
public static void main(String[] args) {
int count = IntStream.rangeClosed(1, MAX)
.mapToObj(n -> String.valueOf(n)) // string으로 변환
.mapToInt(s -> (int)s.chars().filter(c -> c == '8').count()) // char == '8'인 개수
.sum();
System.out.println(count);
}
}
옮기며 배우는 중입니다.
// 1~10000 8의 개수
public void Test2()
{
int cnt = Enumerable.Range(1, 10000).Sum(i => i.ToString().Count(j => j == '8'));
Console.WriteLine("1~10000 수 중 8의 개수 : {0}", cnt.ToString());
}
// 1~10000 8의 개수
public void Test3()
{
string strNum;
int iCnt = 0;
for (int i = 1; i <= 10000; i++)
{
strNum = i.ToString();
foreach (char f in strNum) if (f == '8') iCnt++;
}
Console.WriteLine("1~10000 수 중 8의 개수 : {0}", iCnt.ToString());
}
public class CountingEight {
public static void main(String[] args) {
for (int i=0; i<=10000; i++){
searchEight(i);
}
System.out.println("1에서 10,000 사이에 존재하는 8의 개수는? "+count);
}
private static int count = 0;
public static void searchEight(int num){
if (num%10==8) count++;
if (num>10) searchEight(num/10);
}
}
public static void main(String[] args) { int cnt = 0; for (int i=1; i<=10000; i++) { int a = i % 10; // 1의 자리 int b = i/10 % 10; // 10의 자리 int c = i/100 % 10; // 100의 자리 int d = i/1000 % 10; // 1000의 자리 if(a == 8) cnt++; if(b == 8) cnt++; if(c == 8) cnt++; if(d == 8) cnt++; } System.out.println(cnt); } } // 자바입니다. 다른 분들 코드 굉장하네요
public class Practice{ public static void main(String[] args){
int count=0;
for(int i=1;i<=10000;i++){
if(i/1000==8) count++;
if((i/100)%10==8) count++;
if((i/10)%10==8) count++;
if(i%10==8) count++;
}
System.out.print(count);
}
}
def p393():
print(sum(str(x).count('8') for x in range(1,10001)))
print("".join(str(i) for i in range(1,10001)).count('8'))
print(str(list(range(1, 10001))).count('8'))
#####################################
if __name__ == "__main__":
p393()
def eightselector(x):
result = 0
if x // 1000 == 8: result += 1
if (x % 1000) // 100 == 8: result += 1
if (x % 100) // 10 == 8: result += 1
if (x % 10) == 8: result += 1
return result
print(sum(list(eightselector(n) for n in range(10000))))
아름다운 풀이들 부럽네요
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int Counting(int);
int main() {
int i, count;
count = 0;
for (i = 1; i <= 10000; i++) {
count += Counting(i);
}
printf("%d\n", count);
//getch();
return 0;
}
int Counting(int num) {
char num_ch[6];
int count, length, i;
sprintf(num_ch,"%d", num);
length = strlen(num_ch);
count = 0;
for (i = 0; i < length; i++) {
if (num_ch[i] == '8') {
count++;
}
}
return count;
}
public class Include8 {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i < 10001; i++) {
for (int j = 0; j < (i + "").length(); j++) {
char[] at = (i + "").toCharArray();
if (at[j] == '8') {
count++;
}
}
}
System.out.println(count);
}
}
def counting(number):
cnt = 0
tmp = str(number)
for i in tmp:
if int(i) == 8:
cnt += 1
return cnt
res = 0
for i in range(10001):
res += counting(i)
print(res)
let sumOfEight = 0;
for(let i = 1;i<10000;i++)
{
sumOfEight += String(i).replace(/[^8]/g,"").length;
}
console.log(sumOfEight);
#include <stdio.h>
int main()
{
int i;
int sum = 0;
for(i=1;i<=10000;i++)
{
if(i%10 == 8)
sum++;
if((i%100)/10 == 8)
sum++;
if((i%1000)/100 == 8)
sum++;
if(i/1000 == 8)
sum++;
}
printf("%d",sum);
return 0;
}
tm = " "
for i in range(0,10000):
tm = tm + str(i)
tm
import re
p = re.compile(r'8')
m = p.findall(tm)
len(m)
출력값 : 4000
#include <iostream>
using namespace std;
int main() {
int count = 0;
for (int i = 1; i <= 10000; i++) {
int num = 0;
if (i % 1000==0) {
num = i / 1000;
if (num / 8 == 1) {
count++;
}
num = i - (1000 * (i / 1000));
}
if (i % 100 == 0) {
int num = i / 100;
if (num / 8 == 1) {
count++;
}
num = i - (100 * (i / 100));
}
if (i % 10 == 0) {
int num = i / 10;
if (num / 8 == 1) {
count++;
}
num = i - (10 * (i / 10));
}
if (i % 1 == 0) {
int num = i ;
if (num / 8 == 1) {
count++;
}
num = i - (1 * (i / 1));
}
}
cout << count<<"\n";
return 0;
}
def eight_count():
n = 0
for i in range(1, 10001):
if str(8) in str(i):
n += str(i).count(str(8))
print(n)
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int sum = 0;
Enumerable.Range(1, 10000).ToList().ForEach(e => sum += e.ToString().Count(n => n == '8'));
Console.WriteLine(sum);
}
}
counter = 0 for num in range(1,10001): str_num = str(num) for i in range(0,len(str_num)): #print(len(str_num)) if int(str_num[i]) == 8: counter+=1 print(counter)
def eight_counter(n):
count = 0
for i in str(n):
if i == "8":
count += 1
return count
sum = 0
for i in range(1,10001):
sum += eight_counter(i)
print(sum)
#include <stdio.h>
#include <string.h>
#define MAX 6
int main(void)
{
int i;
int Num = 0;
int cnt = 0;
char buf[MAX];
while(Num <= 10000){
i = 0;
buf[MAX] = {0};
sprintf(buf, "%d", Num);
while(buf[i] != '\0'){
if(buf[i] == '8'){
cnt++;
}
i++;
}
Num++;
}
printf("cnt : %d\n", cnt);
return 0;
}
4000 나왔네요
Python
first = 1
last = 10000
count = 0
for i in range(first, last + 1):
for j in str(i):
if int(j) == 8:
count += 1
print(count)
4000
eight = 0
for x in range(1, 10001):
popList = [int(d) for d in str(x)]
while popList:
if popList.pop() == 8:
eight += 1
print(eight)
4000
static void Main(string[] args)
{
int nCnt, nSum = 0;
string[] mData = new string[10000];
for (int i = 0; i < 10000; i++)
{
mData[i] = i.ToString();
}
for (int k = 0; k < mData.Length; k++)
{
nCnt = mData[k].Length;
for (int m = 0; m < nCnt; m++)
{
if(mData[k].Substring(m,1) == "8")
{
nSum++;
}
}
}
Console.WriteLine(nSum.ToString());
}
eightnum=0
for i in range(1,10001):
stri=str(i)
a=list(stri)
for k in a:
if k=="8":
eightnum+=1
print(eightnum)
def counting(num):
count_8 = 0
for i in range(1, num + 1):
a = str(i)
for j in a:
if(j == '8'):
count_8 += 1
return count_8
n = 315
n_string = str(n)
result = 0
if len(n_string) == 1:
for i in range(n,10000):
i_string = str(i)
for j in range(len(i_string)):
if i_string[j] == n_string:
result+=1
else:
for i in range(n,10000):
i_string = str(i)
start = 0
end = len(n_string)
for j in range(len(i_string)+1-len(n_string)):
if i_string[start:end] == n_string:
result+=1
start+=1
end+=1
print(result)
180730~ kakao 알고리즘 산책
count = 0
for i in range(1, 10001):
kick = str(i)
for j in range(0, len(kick)):
if kick[j:j+1] == "8":
count = count + 1
print(count)
C 언어
#include <stdio.h>
int count = 0;
int i = 0 ;
int main()
{
while( i <10000 )
{
if( ( i / 1000) == 8 ) // 천의 자리
count += 1;
if( ( i % 1000 ) / 100 == 8 ) // 백의 자리
count += 1;
if( ( i % 100) / 10 == 8 ) // 십의 자리
count += 1;
if( ( i % 10 ) == 8 ) //일의 자리
count += 1;
i++;
}
printf("%d", count);
}
//c언어 8이라는 숫자가 총 몇번 나오는지를 확인하는것이기떄문에 모든수를 배열에 저장해버린다.
#include<stdio.h>
int main()
{
int i,j=12;
int arr[50000] = {0, };
int cnt =0;
int count = 0;
for(j=1; j<=10000; j++)
{
i = j;
while(i>0)
{
arr[cnt] = i%10;
//printf("%d", arr[cnt]);
i = i/10;
cnt++;
}
}
for(i=0; i<cnt; i++)
{
if(arr[i]==8)
{
count++;
}
}
printf("%d", count);
}
a = ""
for i in range(1, 10001):
a = a + str(i)
count = a.count('8')
print("1~10000까지의 8이라는 숫자가 총 %d 번나옵니다." %count)
'''
입력받은 숫자의 갯수가 총몇번 나오는지알려줌
a = ""
number = int(input("1~ 10000 까지의 입력한 숫자가 총몇번 나오는지 알려주는 프로그램입니다. 숫자 입력 : "))
while True:
if 0<=number and number<=9:
break;
else:
number = int(input("1~9까지의 범위의 숫자를 입력하세요 : "))
for i in range(1, 10001):
a = a + str(i)
count = a.count(str(number))
print("1~10000까지의 %d 라는 숫자가 %d번 나옵니다." %(number, count))
'''
public class EightCount {
public static void main(String[] args) {
int count = 0;
for(int i=0; i<10000; i++) {
for(int j=i; j>0; j/=10) {
if(j%10 == 8) {
count++;
}
}
}
System.out.println("Count : " + count);
}
}
# .count를 생각을 못 했었네요.....
r = 0
for i in range(1,10001):
for a in str(i):
if int(a) == 8:
r += 1
print(r)
public class test {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 10000; i++)
for (int j = 0; j < (i + "").length(); j++)
count += (i + "").charAt(j) == '8' ? 1 : 0;
System.out.println(count);
}
}
public static void main(String[] args) {
int sum = 0;
for(int i=1 ; i <= 10000 ; i++) {
sum += checkCount(i);
}
System.out.println(sum);
}
public static int checkCount(int number) {
int cnt = 0;
//int res = number;
if(number >= 1000) {
if(number /1000 == 8) cnt++;
number %= 1000;
}
if(number >= 100) {
if(number /100 == 8) cnt++;
number %= 100;
}
if(number >= 10) {
if(number /10 == 8) cnt++;
number %= 10;
}
if(number >= 1) {
if(number /1 == 8) cnt++;
}
return cnt;
}
#include <stdio.h>
int main(){
int i,array_8[10000],sum=0;
for(i=0;i<10000;i++)
array_8[i]=i+1;
for(i=0;i<10000;i++)
sum+=counter(array_8[i]);
printf("%d",sum);
return 0;
}
int counter(n){
int n1=n/1000,n2=(n%1000)/100,n3=(n%100)/10,n4=n%10,count=0;
if (n1==8) count++;
if (n2==8) count++;
if (n3==8) count++;
if (n4==8) count++;
return count;
}
c언어... 멍청하게 푼건가...
public class EightLetterCount {
public static void main(String[] args) {
int cnt = 0;
int[] arr = new int[4];
for(int i = 1; i < 10000; i++) {
arr[0] = i/1000;
arr[1] = i/100 - arr[0]*10;
arr[2] = i/10 - arr[1]*10 - arr[0]*100;
arr[3] = i - arr[2]*10 - arr[1]*100 - arr[0]*1000;
for(int j = 0; j < arr.length; j++){
if(arr[j] == 8) {
cnt++;
}
}
}
System.out.print("cnt: " + cnt);
System.out.println();
}
}
cnt: 4000
이 문제엔 이 방법이 제일 좋은거 같습니다.
#include <iostream>
using namespace std;
int main() {
int InputSize, TargetNumber;
int i, j,count = 0;
cout << "Number Size : 1 ~ ";
cin >> InputSize;
cout << "Target Number : ";
cin >> TargetNumber;
for (i = 1; i < InputSize; ++i) {
for (j = i; j > 0; j /= 10) {
if (j % 10 == TargetNumber)
++count;
}
}
cout << "count : " << count << endl;
//system("pause");
return 0;
}
동적할당으로도 풀어봤지만 이 문제에선 큰 영향이 없는거 같습니다.
#include <iostream>
#include <time.h>
using namespace std;
int* Dictionary;
int TargetNumber;
int calculateCount(int i) {
if (Dictionary[i] != -1)
return Dictionary[i];
if (i < 10) {
if (i == TargetNumber) {
Dictionary[i] = 1;
return 1;
}
else {
Dictionary[i] = 0;
return 0;
}
}
if (Dictionary[i / 10] != -1) {
Dictionary[i] = Dictionary[i % 10] + Dictionary[i / 10];
return Dictionary[i];
}
else {
Dictionary[i] = Dictionary[i % 10] + calculateCount(i / 10);
return Dictionary[i];
}
}
int main() {
clock_t begin, end;
begin = clock();
{
int InputSize;
int i = 0, result = 0;
cout << "Number Size : 1 ~ ";
cin >> InputSize;
cout << "Target Number : ";
cin >> TargetNumber;
InputSize += 1;
Dictionary = new int[InputSize];
memset(Dictionary, -1, sizeof(int)*InputSize); // initialize
int maxcount = result;
for (i; i < InputSize; ++i) {
result += calculateCount(i);
if (result != maxcount) {
//cout << "i : " << i << " / result : " << result << endl;
maxcount = result;
}
}
cout << "result : " << result << endl;
free(Dictionary);
}
end = clock();
cout << "Time : " << (end - begin) / CLOCKS_PER_SEC << endl;
system("pause");
return 0;
}
num_list = []
for i in range(1, 10001):
num_list.append(i)
num8 = 0
for l in num_list:
for m in str(l):
if int(m) == 8:
num8 += 1
print(num8)
public class counteight {
public static void main(String[] args) {
int i = 1;
int sum = 0;
while(i<=10000) {
String num = Integer.toString(i);
for(int j=0; j<num.length();j++) {
if(num.charAt(j)=='8') {
sum += 1;
}
}
++i;
}
System.out.println(sum);
}
}
0000부터 9999까지 총 경우는 10000가지이고 여기에 한 경우당 숫자가 4개 있으므로 총 나오는 숫자의 개수는 40000개 입니다. 그런데 0부터 9까지의 숫자는 나오는 경우가 각각 같아야 합니다. 그래서 40000을 10으로 나눈 4000이 숫자 하나당 나오는 개수라는 것을 알 수 있습니다. 그래서 8이 나오는 개수 또한 4000개 입니다.
public class Answer {
public static void main(String[] args) {
int count = 0;
List<String> list = new ArrayList<>();
for(int i=1; i<10000; i++) {
String s_num = String.valueOf(i);
list.add(s_num);
}
String[] s = list.toArray(new String[list.size()]);
for(int i=0; i<s.length; i++) {
if(s[i].length() ==1 && s[i].equals("8"))
count++;
else if(s[i].length()!=1){
String[] word = s[i].split("");
for(int j=0; j<word.length; j++) {
if(word[j].equals("8"))
count++;
}
}
else
continue;
}
System.out.println("8이 총 등장하는 수 : " + count);
}
}
public class KimSanghyeop
{
public static void main(String[] args)
{
int cnt=0;
int f1;
int temp;
for(f1=1;f1<10000;f1++)
{
temp=f1;
while(temp!=0)
{
if(temp % 10 == 8)
{
cnt+=1;
}
temp = temp /10;
}
}
System.out.println(cnt);
}
}
>>> sum(str(i).count('8') for i in range(10001))
코드를 조금 더 빠르게 하려면 제너레이터를 사용하면 됩니다.
>>> sum((str(i).count('8') for i in range(10001)))
def eight_chk() :
# 10 이하의 숫자에서 8이 나오는 경우, 1
cnt = 1
for i in range(10,10001) :
for j in range(len(str(i))-1,-1,-1):
mok = i // pow(10,j)
if mok == 8 :
cnt += 1
i = i % pow(10,j)
if i==0 : break
return cnt
#include <stdio.h>
int main(void)
{
int n =10000;
int sum = 0;
char catNum='8';
int i,j;
char check[5]={};
for(i=1;i<(n+1);i++)
{
sprintf(check,"%d",i);
for(j=0;j<5;j++)
{
if(check[j]==catNum)
sum++;
}
}
printf("The Number of %c is [%d] in 1...%d\n",catNum,sum,n);
return 0;
}
#findEight.py
num = range(1,10000)
line = " "
for i in num:
line = line + str(i)
print(line)
print(line.count("8"))
n='0'
result=0
while int(n) <10000 :
n=str(int(n)+1)
for i in range(len(n)):
if n[i] =='8':
result +=1
print(result)
n=10000;%1~10000
k=8;%8의 개수
h=ceil(log10(n));%10^(h-1)<n<=10^h
count=0;
for i=1:n
s(1)=i;
for j=1:h-1
m(j)=floor(s(j)/10^(h-j));%10^n 으로 나누기
s(j+1)=s(j)-(10^(h-j))*m(j);
end
m(h)=s(h);
for a=1:h
if m(a)==8
count=count+1;
end
end
end
fprintf('1~%d 까지의 8의 개수 : %d\n',n,count);
#include <iostream>
using namespace std;
int main()
{
int c=0,t=0,mx=10000;
for(int i=0;i<mx;i++){
t=i;
while(t){
if(t%10 == 8) c++;
t/=10;
}
}
cout<<c;
}
word = ''
for x in range(1, 10001):
word = word + str(x)
num1 = len(word)
spl_eight = word.split('8')
word2 = ''
for y in spl_eight:
word2 = word2 + y
num2 = len(word2)
print(num1 - num2)
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
int total = 0;
for (int i = 1; i < 10000; i++)
{
int temp = i;
while (temp != 0)
{
if (temp % 10 == 8)
{
total++;
temp /= 10;
}
else
{
temp /= 10;
}
}
}
Console.WriteLine(total);
}
}
}
public class counts {
private static int count(int n)
{
int cnt = 0;
while (n > 0)
{
if (n % 10 == 8)
{
cnt++;
}
n /= 10;
}
return cnt;
}
public static void main(String[] args)
{
int sum = 0;
for (int i = 1; i <= 10000; i++)
{
sum += count(i);
}
System.out.println(sum);
}
}
public class Ex02 {
public static int func(int num) {
int cnt = 0;
while (true) {
if (num % 10 == 8) {
cnt++;
}
num = num / 10;
if (num / 10 == 0 && num % 10 == 0) {
break;
}
}
return cnt;
}
public static void main(String[] args) {
int start = 1;
int end = 10000;
int sum = 0;
for (int i = start; i <= end; i++) {
sum += func(i);
}
System.out.println(start + "부터 " + end + "까지 8의 개수는 " + sum + "개 입니다.");
}
}
```{.cpp}
using namespace std;
int main(void) { int cnt = 0; string sentence; for (int i = 1; i < 10000; i++) { sentence = to_string(i); for (int i = 0; i < sentence.length(); i++) { if (sentence[i] == '8')cnt++; } } cout << cnt << endl; } ```//문자열로 풀어봤어요~
자바입니다~ 숫자를 String 클래스로 바꿔서 했어요.. 최대한 간략하게 짜보려고 해도 아직 이정도네요 ㅠ
class SumTo10000 { public static void main(String[] args) {
int numOf8=0;
for(int i=8;i<=9998;i++) {
String str = "" + i;
for(int j=0;j<str.length();j++) {
if (str.charAt(j)=='8')
++numOf8;
}
}
System.out.println("number of 8's: " + numOf8);
}
}
자바입니다~
class SumTo10000 {
public static void main(String[] args) {
int numOf8=0;
for(int i=8;i<=9998;i++) {
String str = "" + i;
for(int j=0;j<str.length();j++) {
if (str.charAt(j)=='8')
++numOf8;
}
}
System.out.println("number of 8's: " + numOf8);
}
}
#include <stdio.h>
int main()
{
int num[5];
int cnt = 0;
for (int i = 0; i < 10001; i++)
{
num[0] = i / 10000;
num[1] = i % 10000 / 1000;
num[2] = i % 1000 / 100;
num[3] = i % 100 / 10;
num[4] = i % 10;
for (int j = 0; j < 5; j++)
{
if (num[j] == 8)
{
cnt++;
}
}
}
printf("%d", cnt);
return 0;
}
코딩 잘하시는분들이 부럽습니다
using namespace std;
#include <iostream>
int main ()
{
int count =1;
int quotient,remain;
for (int i=0; i<10000; i++)
{
if (i>9)
{
quotient=i;
while (quotient>9)
{
remain=quotient%10;
quotient=quotient/10;
if (remain==8)
count++;
}
if (quotient==8)
count++;
}
}
cout << count << endl;
return 0;
}
$cnt = 0;
for($i=1; $i<=10000; $i++) for($j=0; $j<strlen($i+""); $j++) if(substr(($i+""), $j, 1) == 8) $cnt++;
echo $cnt;
def FindEight(start,stop):
return str(list(range(start,stop+1))).count('8')
print(FindEight(1,10000))
간단하게 함수형식으로~
문제에서는 10000까지 8이 몇번 나오는지 구하라고 했지만 만약 15000까지 8이 몇번 나오라는지 구하라면 코딩이 필요하지 않을까요?
이런 상황에 대비해 코딩을 해보자면
start=1
upper=15000
what_digit = len(str(upper))
answer=0
for i in range(1 , what_digit):
str_upper = str(upper)
answer += int(str_upper[:-i]) * pow(10,(i-1))
print(answer)
1000의 자리가 8인 수의 개수는 8000~8999로 1000개이다. 다르게 생각하면 8xxx에서 x가 0~9이므로 10^3=1000개 이다. 같은 방법으로 100의 자리, 10의 자리, 1의 자리가 8인 수도 각각 1000개임을 알 수 있다. 따라서 답은 4000개이다.
(근데 이걸 누가 먼저 생각했네요..)
R로 작성했습니다
function1 = function(object, from, to){
input = c()
for(i in from:to){
tmp = strsplit(as.character(i),"")[[1]]
input = append(input, tmp)
}
count = sum(input %in% as.character(object))
return(count)
}
function1(8,0,10000)
#include<iostream>
using namespace std;
int CountEight(int num);
int CountEight(int num){
int Cunum = 0;
if ((num / 1000) == 8){
++Cunum;
}
if ((num / 100) % 10 == 8){
++Cunum;
}
if ((num / 10) % 10 == 8){
++ Cunum;
}
if ((num % 10) == 8){
++Cunum;
}
return Cunum;
}
int main(void){
int sum=0;
int sumnum = 0;
for (int i = 1; i <= 10000; i++){
sumnum = CountEight(i) + sumnum;
}
cout << sumnum << endl;
return 0;
}
num_cnt = 0
for num in range(1,10001):
sep_nums = []
for sep_num in str(num):
sep_nums.append(sep_num)
for sep_num in sep_nums:
if sep_num == '8':
num_cnt += 1
print(num_cnt)
public class Count8 {
public static void main(String[] args) {
int cnt=0;
for(int i = 1;i<=10000;i++) {
Integer num = i;
String str = num.toString();
char[] chArray = str.toCharArray();
for( char ch : chArray){
if(8==Character.getNumericValue(ch)) cnt++;
}
}
System.out.println(cnt);
}
}
public class EightCounting {
public static void main(String[] args){
int count = 0;
for(int i = 0; i <= 10000; i++){
if(i/1000 == 8)
++count;
if((i/100)%10 == 8)
++count;
if((i/10)%10 == 8)
++count;
if(i%10 == 8)
++count;
}
System.out.println(count);
}
}
package problem07;
public class solution {
public static int Eight_counting(int n) {
int count=0;
while(n>0) {
if(n%10==8) {
count+=1;
n=(n-(n%10))/10;
}
else {
n=(n-(n%10))/10;
}
}
return count;
}
public static void main(String[] args) {
int count=0;
for(int i=1; i<=10000;i++) {
count+=Eight_counting(i);
}
System.out.println("1~10,000까지 숫자 8은 총 "+count+"번 나왔습니다.");
}
}
let result = 0
for(let i = 1; i<=10000; i++){
// const memory = []
const splitted = String(i)
for(let j = 0; j<splitted.length; j++){
if(splitted[j] === '8')
result += 1
}
}
console.log(result)
//결과: 4000
count = 1;
for i in range(11, 10001) :
i = str(i)
for j in range(len(i)) :
if i[j] == '8' : count+=1
print(count)
count=0
for num in range(0,10000):
num=list(str(num))
for eight in num:
if (eight=='8'):
count+=1
print(count)
total = 0
for i in range(10000):
str_i = str(i)
count_eight = str_i.count('8')
total += count_eight
print(total)
import re
box = 0
p = re.compile('(0|1|2|3|4|5|6|7|9)')
for i in range(1,10001):
b = str(i)
m = p.sub('',b)
box += len(m)
print(box)
cn=0
for j in [str(i) for i in range(10000) if '8' in str(i)]:
print(j)
for i in j:
if i == '8':
cn += 1
cn
result = 0
for n in range(1,10000):
kkk = 0
for i in str(n):
if i=='8':
kkk+=1
result +=kkk
print(result)
count = 0
for i in range(1, 10001):
for j in range(0, int(len(str(i)))):
if int(str(i)[j]) == 8:
count += 1
else:
pass
print(count)
c언어 입니다
#include <stdio.h>
int main(){
int num,digit,count = 0;
for(int i=1; i<=10000;i++){
num = i;
while(1){
digit = num % 10;
if(digit==8){
count++;
}
if(num>=10){
num /= 10;
}
else
break;
}
}
printf("1부터 10000까지 8은 %d번 나옵니다", count);
}
print(range(1,21)) a = range(1,21) print('a:',a)
a = list(range(1,21)) print('a:',a)
a = str(list(range(1,21))) print('a:',a)
print(str(list(range(10001))).count('8'))
package test;
public class test4 {
public static void main(String[] args) {
int Cnt = 0;
for(int i=1;i<=10000; i++) {
int fromIndex = -1;
String num = Integer.toString(i);
while ((fromIndex = num.indexOf("8", fromIndex + 1)) >= 0) {
Cnt++;
}
}
System.out.println(Cnt);
}
}
public class practice {
public static void main(String[] args) {
int cnt = 0;
for (int i = 1; i < 10000; i++)
{
if (i % 10 == 8) cnt++;
if (i >= 10 && i < 100)
{
if(i / 10 ==8) cnt++;
}
else if (i >= 100 && i < 1000)
{
if(i / 100 ==8) cnt++;
if(i / 10 % 10 == 8) cnt++;
}
else
{
if(i / 1000 == 8) cnt++;
if(i / 100 % 10 == 8) cnt++;
if(i / 10 % 10 == 8) cnt++;
}
}
System.out.println(cnt);
}
}
#include <stdio.h>
int main ()
{
int i,j,c=0;
int count=0;
for(i=1;i<=10000;i++)
{
c=i;
for(j=1;i>j;j*=10)
{
if(c%10==8)
{
count++;
c=c/10;
}
else
{
c=c/10;
}
}
}
printf("%d",count);
return 0;
}
count = []
for i in range(10000):
k = i+1
for j in str(k):
if j =='8':
count.append(1)
print(sum(count))
numList=[str(i) for i in range(1,10000)]
cnt = 0
for num in numList:
for i in range(len(num)):
if num[i] == '8':
cnt+=1
print(cnt)
```
for(; num<10000; num++) {
i = num/1000;
j = (num%1000)/100;
k = (num%100)/10;
l = num%10;
if(i == 8)
count++;
if (j==8) {
count++;
}if (k==8) {
count++;
}if (l==8) {
count++;
}
}
old func은 O(N), new) new_func은 O(1)
int old_func (int N)
{
int cnt = 0;
for(int i = 1 ; i <= N; ++i)
{
for (int j = 1; i / j > 0; j *=10) {
if((i / j) % 10 ==8 )
cnt++;
}
}
return cnt;
}
int new_func (int N)
{
int cnt = 0;
for(int i = 1; N/ i > 0; i *=10)
{
if((N / i) % 10 <= 7)
{
cnt += (N / (10 * i)) * i;
}
else if((N / i) % 10 == 8)
{
cnt += (N / (10 * i)) * i + 1 + (N % i);
}
else
{
cnt += (N / (10 * i) + 1) * i;
}
}
return cnt;
}
ans=0
for i in range(10000):
ans+=str(i).count('8')
print(ans)
유투브에서 재즐보프님의 영상으로 파이썬을 시작하게 되었는데, 그때의 연습문제 동영상으로 이 문제가 있었던적이 떠오릅니다. 자세히 기억이 나지는 않지만은, 그래도 어떤 방식으로 풀었는지는 대강 기억이 납니다. 그래서 그것을 직접 적용하려고 했더니만, 이미 코딩할 필요도 없이 손계산으로 풀어져버려서 어떻게 코딩을 해야하는가 고민하고 있었읍니다. 마치 수능문제에 출제되어도 이상하지 않을 난이도의 문제라 잠시 길을 잃었는데, 범위를 잘 보니, 완전탐색법을 써도 계산 횟수가 1만회 정도이기 때문에 시간이 그리 걸리지는 않을것 같아서 꽤 우직한 풀이를 하였읍니다.
a=range(1,10000)
check=0
for i in a:
j=str(i)
for k in range(len(j)):
if int(j[k])==8:
check+=1
else:
pass
print(check)
답 4000
#1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
#8의 개수
total = 0
for i in range(1,10000):
number = str(i)
find = number.count('8')
total += find
print(total)
#include <iostream>
int count = 0;
void myGenerator(int a)
{
int units = 0;
int tens = 0;
int hundreds = 0;
int thousands = 0;
if (a < 10) // 1~9
{
if (a == 8)
count++;
}
else if (a < 100 && a > 9) // 10~99
{
units = a % 10;
tens = a / 10;
if (units == 8)
count++;
if (tens == 8)
count++;
}
else if (a < 1000 && a > 99) // 100 ~ 999
{
hundreds = a / 100;
tens = a / 10;
tens = tens % 10;
units = a % 10;
if (units == 8)
count++;
if (tens == 8)
count++;
if (hundreds == 8)
count++;
}
else if (a <= 10000 && a > 999) // 1000 ~ 5000
{
thousands = a / 1000;
//std::cout << thousands << std::endl;
hundreds = a / 100;
hundreds = hundreds % 10;
//std::cout << hundreds << std::endl;
tens = a / 10;
tens = tens % 10;
//std::cout << tens << std::endl;
units = a % 10;
//std::cout << units << std::endl;
if (units == 8)
count++;
if (tens == 8)
count++;
if (hundreds == 8)
count++;
if (thousands == 8)
count++;
}
}
int main()
{
for (int i = 0; i <= 10000; ++i)
myGenerator(i);
std::cout << count << std::endl;
}
int main() { int a=0, b=0, c=0, d=0; int count=0; for(;;) { d++; if(d==8) count++; if(c==8) count++; if(b==8) count++; if(a==8) count++; if(d==10) { c++; d=0; } if(c==10) { b++; c=0; } if(b==10) { a++; b=0; } if(a==10) break; printf("%d%d%d%d\n", a, b, c, d); } printf("%d", count); }
member=range(1,10000)
box=[]
for i in member:
a=str(i)
for ii in a:
if ii=='8':
box.append(ii)
print(len(box))
답은 4000 이군요... 짧게 가고싶은데..
class Solutions {
int[] nums_array;
int count = 0;
Solutions() {
nums_array = new int[10000];
for(int i = 0; i < nums_array.length; i++) {
nums_array[i] = i+1;
}
}
int Check_for_8() {
for(int i = 0; i < nums_array.length; i++) {
int para = nums_array[i];
while(para!=0) {
if(para%10 == 8) {
count++;
}
para /= 10;
}
}
return count;
}
}
class Count_of_8 {
public static void main(String[] args) {
Solutions slt = new Solutions();
System.out.print("결과: " + slt.Check_for_8());
}
}
8 _ _ 은 총 1000개, ( _ 은 000 부터 999 까지 있다.) _ 8 _ 도 1000개, 이런 꼴이 4개 니까 4 * 1000 = 4000. 정답은 4000개. - Made by GPS
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int cnt = 0;
for(int i = 0 ; i < 10001; i++) {
String k = Integer.toString(i);
for(int j = 0 ; j < k.length(); j++) {
if(k.charAt(j) == '8') {
cnt++;
}
}
}
System.out.println("1부터 10000까지 8이 들어간 횟수 : "+ cnt);
}
}
count=0
for i in range(1,10001):
if "8" in str(i):
for coun in str(i):
if coun =="8":
count+=1
print(count)
import math
rs = 0;
for i in range(1,10001,1):
o = math.trunc(i/10000)
a = math.trunc(i/1000) #ex i= 2645 a = 2
b = math.trunc((i-(a*1000))/100) #b = 6
c = math.trunc((i-(a*1000)-(b*100))/10)
d = (i-(a*1000)-(b*100)-(c*10))
num = [o,a,b,c,d]
for t in num:
if(t == 8):
rs= rs+1
print("8의 갯수",rs)
tmp = 1
count = 0
while tmp <= 10000 :
i = tmp
i = list(str(i))
for j in range(len(i)) :
if i[j] == '8' :
count += 1
tmp += 1
print(count)
N = 10001
counter = 0
for i in range(1, N):
numStr = str(i)
for j in range(len(numStr)):
if numStr[j] == '8':
counter += 1
print(counter)
python
a = list(range(1, 10001)) # 1~10001까지의 정수 리스트 a 생성
b = ''.join(map(str, a)) # 리스트 a의 요소들을 문자열로 바꾼 뒤 공백을 기준으로 join
print(b.count('8')) # 8의 카운트값 출력
파이썬
man = list(range(1,10001))
eight = 0
for n in man:
a = str(n).count('8')
eight += a
print(eight)
def solution(n):
c = 0
for i in range(1,n+1):
i = str(i)
for j in range(len(i)):
if i[j] == '8':
c += 1
return c
print(solution(10000))
public class Number {
public static void main(String[] args) {
int count = 0;
for(int i=1; i<=10000; i++) {
String str = null;
str = "" + i;
for(int j=0; j<str.length(); j++) {
if(str.charAt(j) == '8') {
count++;
}
}
}
System.out.println("8의 총수량은 : " + count);
}
}
답은 4000 나옵니다
public class eightCount {
public static void main(String[] args) {
int start=1, range=10000, count=0;
for (int i = start; i<(start+range); i++) {
String str = Integer.toString(i);
for(int j = 0; j < str.length(); j++) {
if((str.charAt(j)-'0')==8) {
count++;
}
}
}
System.out.print(start + "과 " + (start+range-1) +"까지 8의 갯수는 " + count + "개 입니다.");
}
}
x=[str(i) for i in range(1,10000)]
q=0
for i in x:
if '8' in x:
q+=i.count('8')
print(q)
``````{.python}
print(str(list(range(1,10001))).count('8'))
def multiples(num):
cnt = 0
for i in range(num):
for j in str(i):
if int(j) == 8:
cnt += 1
return cnt
print(multiples(10000))
def count():
string=""
for i in range(1, 10001):
string += str(i)
return(string)
string=count()
c8=string.count("8")
print(c8)
많이 배우고 갑니다! 분발하겠습니다!
저는 C를 이용했습니다!
#include <Stdio.h>
/*1~10000까지 8이 몇 개가 있을지
나의 생각:숫자가 들어오면 그 숫자를 각 자릿수로 쪼갠다
*/
#define LIMIT_MAX 10000
int jari(int value)
{
int jari = 0;
while (value != 0)
{
jari++;
value = value / 10;
}
return jari;
}
int main()
{
int space[5] = { NULL };
int count = 0;
int value = 0;
int digit = 0;
for (int i = 0; i < LIMIT_MAX; i++)
{
digit = jari(i + 1);
value = i + 1;
int index = 0;
while (value > 0)
{
space[index] = value % 10;
index++;
value = value / 10;
}
for (int j = 0; j < digit; j++)
{
//자릿수 크기의 배열에서 생각
if (space[j] == 8)
{
count++;
}
}
}
printf("1에서 10000까지 8의 개수는 %d개 입니다\n", count);
}
count8: int = 0
for num in range(1, 10001):
for a in str(num):
if '8' == a:
count8 += 1
print(count8)
def prob(num): # 1부터 n까지의 입력을 받음, 또한, n값은 1000, 100000 같은 형태로 받음
n=len(str(num))
cnt = n-1 # 모든 자리의 수가 8인 경우를 설정.
for i in range(1,(n-1)):
cnt += 9**(n-1-i)*comb(n-1,i)*i
print(cnt)
def fac(num):
if num==1:
return 1
return num*fac(num-1)
def comb(num1,num2): # (num1) C (num2)
return fac(num1)/(fac(num2)*fac(num1-num2))
eight = 0
for x in range(1,10001) :
for i in str(x) :
if i == '8' :
count = count +1
print(eight, " times")
cnt=0
for i in range(1,10000):
a=str(i)
n=len(a)
for j in range(0,n):
if '8' in a[j]:
cnt+=1
print(cnt)
from random import *
sum = 0
for i in range(1,10001):
k = str(i)
count = k.count('8')
sum +=count
print(sum)
package sec01.exam01;
public class HelloJava {
public static void main(String[] args) {
int i, temp, count = 0;
for (i = 1; i <= 10000; i++)
{
temp = i;
while (i > 0)
{
if (i % 10 == 8)
count++;
i /= 10;
}
i = temp;
}
System.out.println("1부터 10000까지 수에서 8의 개수 = " + count + "\n");
}
}
temp를 안 넣고 하니 컴파일 할 때 프리징이 오네요... 아마 for 문 내에서 while 문 실행 시 i가 바뀌었고, 그 바뀐 i 값 때문에 반복문이 작동하지 않는다 생각해 temp로 기존 i값을 보존하는 방법을 사용하긴 했습니다. 제가 생각한 원인이 맞나요? 기존 코드는 temp = i; , i = temp; 를 넣지 않았습니다.
int cnt = 0;
for(int i=1; i<10000; i++) {
char[] num = Integer.toString(i).toCharArray();
for(char ch : num) {
String str = String.valueOf(ch);
if("8".equals(str)) cnt++;
}
}
System.out.println(cnt);
1부터 10000까지 숫자를 toString.toCharArr()로 바꾼 후 i<toCharArr.length까지 arr[i]에 대해== "8"이면 cnt++ 답 : 4000
count = 0;
for (int i = 1; i <= 10000; i++)
for (int j = i; j > 0; j /= 10)
count += j % 10 == 8 ? 1 : 0;
Console.WriteLine(count);
anw=0
for i in range(1,10001):
if i%10000-i%1000==8000:
anw+=1
if i%1000-i%100==800:
anw+=1
if i%100-i%10==80:
anw+=1
if i%10==8:
anw+=1
print(anw)
class Solution(object):
def count_8(self, num):
cnt = 0
while num > 0:
num, rem = divmod(num, 10)
if rem is 8:
cnt += 1
return cnt
if __name__ == "__main__":
sol = Solution()
cnt = 0
for val in range(1, 10001):
cnt += sol.count_8(val)
print cnt
temp = 0
for i in range(1,10001):
comp_str= str(i)
for ch in range(len(comp_str)):
if '8' == comp_str[ch]:
temp += 1
print(temp)
public class Number8 {
static int counter=0;
public void chk(int chker) {
if(chker==8) {counter++;
}
}
public static void main(String[] args) {
Number8 number = new Number8();
for(int i=1; i<=10000; i++) {
int a,b,c,d;
a=i/1000%10;
b=i/100%10;
c=i/10%10;
d=i%10;
number.chk(a);
number.chk(b);
number.chk(c);
number.chk(d);
}
System.out.println(counter);
}}
import java.util.*;
public class 구글입사문제중에서 {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
String[] list = new String[10001];
for(int s = 0; s<list.length; s++) {
list[s] = String.valueOf(s);
}
for(int k=0; k<list.length; k++) {
String[] num = list[k].split("");
int count = 0;
for(int l=0; l<num.length; l++) {
if(num[l].equals("8")) {
count++;
}
}
nums.add(count);
num = null;
}
int sum=0;
for(int a=0; a<nums.size(); a++) {
sum+=nums.get(a);
}
System.out.println(sum);
}
}
//제가 너무 어렵게 푼 것 같네요...
//다른분들 대단하네요..
파이썬 3.6 입니다
def count_eight(n):
number_pool = (n for n in range(1, n + 1))
counter = 0
for i in number_pool:
counter += [c for c in str(i)].count('8')
return counter
print(count_eight(10000))
def count8(n):
result = 0
for i in str(n):
if i == '8':
result += 1
return result
A = [count8(i) for i in range(1,10001)]
print(sum(A))
정수 n 내에 존재하는 8의 갯수를 찾는 함수를 만들고, 1부터 10000까지 숫자에 대해 함수를 실행하여 합을 구함
B = ''
for i in range(1,10001):
B += str(i)
sum_ = 0
for i in B:
if i == '8':
sum_ += 1
print(sum_)
1부터 10000까지 문자열로 붙여 쓴 다음, 문자열 인덱싱을 통해 8을 찾을때마다 sum을 1씩 더해서 최종 값을 출력
굳이 사용해본 반복문 in 파이썬3
result = 0
for i in range(1, 10001):
for j in str(i):
if j == '8':
result += 1
print(result)
l=[]
for n in range(1,10001):
n=str(n)
if "8" in n:
l.append(n)
ec=0
for k in l:
en=k.count("8")
ec+=en
print(ec) #4000
# 또는 아래와 같이 한줄로 간단하게
print(str(list(range(1,10001))).count("8"))
파이썬
number=[str(i) for i in range(1,10001)]
count=0
for j in number:
for k in j:
if int(k) == 8:
count += 1
print(count)
# 4000
Javascript(ES6)...
`1 부터 10,000 까지의 숫자를 하나의 긴 문자열로 생성, 그 문자열에서 '8' 숫자만을 정규식으로 추출하여 추출된 배열 길이 측정`;
let result;
result = [...Array(10001).keys()].slice(1); // 1 ~ 10,000 까지 숫자가 채워진 배열 생성
result = result.join(''); // 배열안에 있는 숫자를 이어붙여 하나의 문자열로 생성
result = result.match(/8/g).length; // 문자열에서 8 만 추출하여 배열을 생성, 그 길이를 잼
console.log(result); // 4000
Python 3...
print(''.join([str(i) for i in range(1,10001)]).count('8'))
#include<stdio.h>
int main(){
int i, sum=0;
for(i=1;i<=10000;i++){
int a=i/1000;
int b=(i-a*1000)/100;
int c=(i-a*1000-b*100)/10;
int d=i%10;
if(a==8) sum++;
if(b==8) sum++;
if(c==8) sum++;
if(d==8) sum++;
}
printf("%d",sum);
}
package codingdozang;
public class Count8 {
public static void main(String[] args) {
int i, sum=0;
for(i=1;i<=10000;i++) {
int a=i/1000;
int b=(i%1000)/100;
int c=(i%100)/10;
int d=i%10;
if(a==8) sum++;
if(b==8) sum++;
if(c==8) sum++;
if(d==8) sum++;
}
System.out.println(sum);
}
}
finCnt = 0
numList = list(map(str,range(1,10001)))
tmp = []
for i in numList:
for j in i:
if j == '8':
finCnt += 1
print(finCnt)
N = 10000
count = 0
for i in range(N + 1):
for j in range(len(str(i))):
count += (str(i)[j] == '8')
print('1부터 {0}까지 8이라는 숫자는 {1}번 나온다'.format(N, count))
class CT { int counter = 0;
int count(int i) {
if(i / 1000 == 8) { ++counter; }
if((i % 1000) / 100 == 8) { ++counter; }
if((i % 100) / 10 == 8) { ++counter; }
if(i % 10 == 8) { ++counter; }
return counter;
}
}
public class 구글_8개수세기 { public static void main(String[] args) { CT c = new CT();
int total = 0;
for(int i = 1; i <= 10000; i++)
{
c.counter = 0;
total += c.count(i);
}
System.out.printf("1 ~ 10000까지 8의 개수는 %d개이다.", total);
}
} 정답은 4000입니다. ( JAVA )
public class FindNumber {
public static void main(String[] args) {
int count =0;
for(int i = 1; i<=10000; i++) { //1부터 10000까지 8이나오는 횟수 찾기
if(i%10 == 8) { //1의 자리
count++;
}
if(((i/10)%10)==8) { //10의 자리
count++;
}
if(((i/100)%10)==8) { //100의 자리
count++;
}
if(((i/1000)%10)==8) { //1000의 자리
count++;
}
if(i==10000) {
break;
}
}
System.out.println("정답: "+ count);
}
}
c = 0
for x in range(1, 10000):
a = [int(a) for a in str(x)]
b =(int(a.count(8)))
c = b+c
print(c) ```
a = []
for b in range(1,10001):
a.append(b)
print(a.count(8))
c = list(map(str,a))
d = "".join(c)
print(d.count('8'))
result = 0
for i in range(1,10000):
str_i = str(i)
len_i = len(str_i)
for j in range(len_i):
if '8' in str_i[j]:
result +=1
print(result)
eight = 0
for i in range(1, 10000):
num = list(str(i))
for j in range(0, len(num))
num[j] = int(num[j])
if 8 in num:
eight += 1
j += 1
파이썬 3.8.1 입니다.
#-*- coding:utf-8 -*-
result = [] # 결과 도출용 리스트
for x in range(1,10000):
result.extend([int(n) for n in str(x)]) # 각 자리 숫자를 뽑아 리스트 삽입
print(result.count(8)) # 8의 갯수
a = list(i for i in range(1,10001))
sum = 0
for i in range(len(a)):
a[i] = str(a[i])
if a[i].count('8') != 0:
sum += int(a[i].count('8'))
print(sum)
from pandas import Series, DataFrame
a=Series(range(1,10001)).astype(str)
def count_8(x):
return(x.count('8'))
a.apply(count_8).sum()
cnt=0
for i in range(10001):
if i%10==8 :
cnt=cnt+1
elif (i%100)//10 ==8:
cnt =cnt+1
elif (i%1000)//100 ==8:
cnt=cnt+1
elif i//1000 ==8:
cnt=cnt+1
print(cnt)
python
count=0
for i in range(0,10001):
str_i = str(i)
for n in range(0,len(str_i)):
if str_i[n-1]=='8':
count += 1
print(count)
#include<iostream>
#include<string>
using namespace std;
/*
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
*/
//정답: 4000
void Func(int n) {
int count = 0;
int c;
bool check;
for (int i = 1; i <= n; i++) {
string s = to_string(i);
c = 0;
check = false;
for (int j = 0; j < s.length(); j++) {
if (s[j] == '8') { ++count; ++c; check = true; }
}
if (check) { cout << s << " = " << "8개수:" << c << endl; }
}
cout << "1부터" << n<<"까지 8의 총 개수는=" << count << endl;
}
int main() {
Func(10000);
}
a = range(1, 10000)
b = str(list(a))
howmany = 0
for i in b:
if '8' in i:
howmany += 1
print(howmany)
def count_8(n): global sum
if (n==8):
sum+=1
return sum
def divid(m): global sum
str_m=str(m)
len_m=len(str_m)
for i in range(len_m):
count_8(int(str_m[i]))
print('8의 갯수는:',sum)
sum=0 divid(88558)
count = 0
for i in range(1, 10001):
t_str = str(i)
for j in range(len(t_str)):
if t_str[j:j+1] == '8':
count += 1
print('1~10000범위에 8이 들어간 횟수는 {}번 입니다'.format(count))
저도 언젠가는 다른 분들 처럼 언어를 잘 알아서 알고리즘을 세워 한줄로 코딩하는 날이 오겠죠..
_sum = 0
a = 0
for i in range(1,10001):
a = str(i)
if a.count('8') >= 1:
_sum += a.count('8')
print(_sum)
파이썬 / 한줄짜리 코드가 정말 많네요.
char Number[5] = {0, };
int nCount = 0;
for(int c = 1 ; c <= 10000 ; c++)
{
itoa(c, Number, 10);
for(int i = 0 ; i < strlen(Number) ; i++)
{
if(Number[i] == '8')
{
nCount++;
}
}
}
count=0
for i in range(1,10001):
chr=str(i)
for i in range(len(chr)):
if chr[i]=="8":
count+=1
print(count)
파이썬입니다.
num = []
counting = []
for x in range(1,10001):
num.append(x)
for x in num:
for i in str(x):
if int(i) == 8:
counting.append(i)
print(len(counting))
def iterate8s(lower, upper):
result = 0
for i in range(lower, upper+1):
while i:
if i % 10 == 8:
result += 1
i /= 10
i = int(i)
else:
i /= 10
i = int(i)
return result
생각 없이 풀었습니다.
function getNumber(num) {
num = num.toString();
var index = 0;
var count = 0;
while(num[index]) {
if(num[index].match("8")) { count++;}
index++;
};
return count;
}
var countResult = 0;
for(var index = 0; index < 10000; index++){
countResult += getNumber(index);
}
console.log(countResult);
count = 0
for i in range(10000):
for j in range(len(str(i))):
if str(i)[-j] == '8':
count += 1
print(count)
def cal(num):
global count
for m in range(1,len(str(num))):
ma=num%10
num=num//10
if ma==8:
count+=1
if num==8:
count+=1
count=0
for i in range(1,10001):
cal(i)
print("결과 : ", count,"회")
파이썬 왕초보입니다. 위와 같은 방법으로 구하면 결과가 3999회가 나오는데 무엇이 잘못된 것인가요? 아무리 생각해봐도 제 능력으로 구현할 수 있는 logic은 이것밖에 없었습니다.
numbers = []
for num in range(10001):
for i in str(num):
if '8' in i:
numbers.append('8')
print(numbers.count('8'))
#매핑으로 str->int 로 바꿔서 더하려고했으나 count함수로 그냥 리스트에있는 스트링을 더했습니다
#a = map(int, numbers)
#파이썬 코딩 공부 제대로 한지 4일차인 코린이입니다..
#드디어 처음으로 문제 풀었네요 코드도 길고 장황하지만ㅠ 기뻐서올립니다
c = []
for i in range(1,10001):
for a in str(i):
b = int(a)
c.append(b)
print(f"{c.count(8)}")
정답은 4,000개 맞나요?!
count8 = 0
for i in range (1,10001):
if i//1000 == 8 :
count8 += 1
if (i-(i//1000)*1000)//100 == 8 :
count8 += 1
if (i-(i//100)*100)//10 == 8 :
count8 += 1
if (i-(i//10)*10) == 8 :
count8 += 1
답은 4000
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("찾고 싶은거 뭐임:");
int find = scan.nextInt();
for(int i=1;i<=10000;i++)
{
search(find,i);
}
System.out.println("총 갯수: " + result);
}
private static int result=0;
public static void search(int find,int num) {
if(num%10 == find)
result++;
if(num>10)
search(find,num/10);
}
}
파이썬 입니다.
count=0
for i in range(1,10001):
b=str(i)
a = list(b)
if '8' in a:
for i in a:
if i=='8':
count+=1
else:
pass
else:
pass
print(count)
package test;
import java.util.*;
public class Test{
public static void main(String[] args) {
int i = 1;
int count = 0;
ArrayList<String> arr = new ArrayList<>();
while(i<=10000) {
arr.add(Integer.toString(i));
i++;
}
for(String e : arr) {
for(int j = 0; j<e.length(); j++) {
if(e.charAt(j) == 56)
count++;
}
}
System.out.print(count);
}
}
파이썬으로 작성하였습니다.
eight_counts = 0
for num in range(1,10001):
for x in str(num):
if int(x) == 8:
eight_counts += 1
print(eight_counts)
package example01;
public class Google2 {
public static void main(String[] args) {
int count=0;
//무식하게 해봣습니다
for(int a=0;a<10;a++) {
for(int b=0;b<10;b++) {
for(int c=0;c<10;c++) {
for(int d=0;d<10;d++) {
if(a==0) {
count++;
}
if(b==0) {
count++;
}
if(c==0) {
count++;
}
if(d==0) {
count++;
}
}
}
}
}
System.out.println(count);
}
}
public class test4 {
public static void main(String[] args) {
String hatena = "";
int answer = 0;
for(int a = 0; a < 10000; a++) {
hatena += String.valueOf(a);
}
for(int i = 0; i < hatena.length(); i++) {
if(hatena.charAt(i) == '8') {
answer++;
}
}
System.out.println("정답 : "+ answer);
}
}
구글이 원한 답은 아니겠죠? ㅋㅋㅋ
#먼저 숫자 범위를 입력 받음.(a=1,b=10000)
#숫자 범위 만큼 for문을 돌린다.
#8728이들어왔다고 치면
#i라는 숫자를 문자로 변환 시켜준다. str() 함수는 정수를 문자열로 반환해줌.
#그러면 8728이라는 숫자는 check ['8','7','2','8']과 같음
#이제 list의 내장 함수인 count를 이용함.
#count('1')이 오면 리스트 안에 '1'라는 문자가 몇개 있는지 확인함.
#따라서 check.count('8')을 하면 check 안에 있는'8'이라는 문자의 갯수를 확인하고 반환해줌.
#그 숫자를 number을 통해서 덧셈을 계속 해주면 됨.
def solve(a,b):
number = 0
c = []
for i in range(a,b+1):
check = str(i)
#---------없어도 되는 부분----------
if '8' in check:
c.append(i) #이건 그냥 밑에 있는 8들어간 숫자 보여줄려고 있는 코드임.
#-----------------------------------
number += check.count('8')
print("count = %d"%number)
#8이 들어간 숫자들을 볼려면 주석을 해제하면 됨
"""
count = 1
for i in c:
print(str(count),i)
count+=1
"""
#include<stdio.h>
int main()
{
int i,j,c=0;
for(i=1;i<=10000;i++)
{
for(j=1;j<=10000;j*=10)
{
if((i/j)%10==8)
c++;
}
}
printf("%d",c);
return 0;
}
j 부분이 포인트
using System;
using System.Text.RegularExpressions;
namespace _62일차_10월02일
{
class MainApp
{
static void Main(string[] args)
{
string Data = "";
for (int i =1; i < 10000; i++)
{
Data += i.ToString();
}
MatchCollection matches = Regex.Matches(Data, "8");
int cnt = matches.Count;
Console.WriteLine($"Result = {cnt}개");
}
}
}
public static int countNum(int target, int number) {
int count = 0;
for (int i = 1; i < target+1; i++) {
int n = i;
if(n<10) {
if(n%10==number) count++;
}else if(n>9) {
while(n>0) {
if(n%10==number) count++;
n = n/10;
}
}
}
return count;
}
자바입니다.```{.java} public class google {
public static void main(String[] args) {
int count = 0;
for(int i=1;i<=10000;i++) {
int a=i;
while(a/10>=0) {
if(a%10==8) {
count++;
}
if(a/10<1) {
break;
}
a/=10;
}
}
System.out.println(count);
}
} ```
num = []
for i in range(10000):
i = str(i)
num.append(i)
num_2 = "".join(num)
num_2
num_2.count('8')
li1 = []
for x in range(1,10001):
x = str(x)
if x.count('8')!=0:
y = x.count('8')
li1.append(y)
else:
pass
print(sum(li1))
python 3.9.0
package codeDojang;
import java.util.Scanner;
public class Prac {
public static void main(String[] args) {
int cnt=0;
for(int i=1;i<=10000;i++) {
int tmp = i;
while(tmp/10!=0) {
if(tmp%10==8) {
cnt++;
}
tmp/=10;
}//end while
if(tmp%10==8) cnt++;
}
System.out.println(cnt);
}
}
def counter8(text):
count = 0
for i in range(1,text):
for aa in list(str(i)):
if aa == '8':
count += 1
return count
print(counter8(10000))
package main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int cnt = 0;
String[] str = new String[10000];
for (int i = 0; i < str.length; i++) {
str[i] = " "+ i;
}
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str[i].length(); j++) {
if(str[i].charAt(j)=='8') {
cnt+=1;
}
}
System.out.println(str[i]+" "+cnt);
cnt = 0;
}
}
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
int count=0;
int i=10000;
int a=0;
int _a;
while(i--) {
_a=a;
while (_a!=0) {
if(_a%10==8) {
count++;
}
_a=_a/10;
}
cout << i << endl;
a++;
}
cout << count << endl;
return 0;
}
public class Numberof8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//1부터 10000까지 8의 개수
int a=0, b=0, c=0, d=0;
int num=0;
for(int i=0; i<10000; i++) {
a=i%10;
b=i/10%10;
c=i/100%10;
d=i/1000;
if(a==8) num++;
if(b==8) num++;
if(c==8) num++;
if(d==8) num++;
}
System.out.println("1부터 10000까지 8의 개수는 : "+num);
}
}
#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio();
int countdata = 0;
for (int i = 1; i <= 10000; ++i) {
string data = to_string(i);
for (int i = 0; i < data.length(); ++i) {
if (data[i] == '8') {
countdata++;
}
}
}
cout << countdata << endl;
}
a = []
for i in range(1, 10001):
a += list(str(i))
print(a.count("8"))
파이썬으로 작성했습니다.
1부터 10,000까지의 자연수를 분리하여 리스트에 넣고, 해당 리스트에서 8을 세어 출력했습니다.
정답은 4000 입니다.
def fac(num):
mul = 1
for i in range(1,num + 1):
mul *= i
return mul
def fcombination(num):
a = 1
for i in range(0, num):
a *= (4 - i)
f = fac(num)
return a / f
s = 0
for count in range(1,4):
result = fcombination(count)
result = result * 9**(4-count) * count
s += result
print((s + 4))
학실히 경우의 수로 푸니까 루프 별로 안돌아서 좋네요
JavaScript
let arr = Array.from({length: 10000}, (v , i) => i + 1);
let count = arr.join('').match(/8/g).length;
console.log(count); // 4000
정답 : 4000
count = 0
for i in range(10000):
if i >= 1000 and i < 10000:
a = i//1000
b = (i%1000)//100
c = (i%100)//10
d = (i%10)//1
if a == 8:
count += 1
if b == 8:
count += 1
if c == 8:
count += 1
if d == 8:
count += 1
elif i >= 100 and i < 1000:
b = i // 100
c = (i % 100) // 10
d = (i % 10) // 1
if b == 8:
count += 1
if c == 8:
count += 1
if d == 8:
count += 1
elif i >= 10 and i < 100:
c = i // 10
d = (i % 10) // 1
if c == 8:
count += 1
if d == 8:
count += 1
elif i >= 1 and i < 10:
d = i
if d == 8:
count += 1
print(f'1부터 10000까지의 숫자중에 8이 나오는 횟수는 {count}')
Python입니다.
a = 0
>>> for i in range(1, 10000):
... b = list(str(i))
... a += b.count('8')
...
>>> print(a)
4000
결과는 4000입니다.
def find8(n):
length = len(str(n))
count = 0
high = n // pow(10, length - 1)
if n > 10:
if high < 8:
count = high * (length - 1) * pow(10, length - 2)
elif high == 8:
count = high * (length - 1) * pow(10, length - 2) + n % pow(10, length - 1)
else:
count = high * (length - 1) * pow(10, length - 2) + pow(10, length - 1)
return count + find8(n % pow(10, length - 1))
else:
if n > 8:
return 1
else:
return 0
print(find8(10000))
정면돌파 해봤습니다. 저 함수에 뭘 넣던 넣어준 수보다 작은 수들의 8의 갯수를 세 줍니다. 10^n 보다 작은 수들의 8의 갯수 총합은 n * 10^(n-1)임을 이용했습니다.
재귀 호출로 n자리 수를 찾고, n-1, n-2 ... 1자리 수에서 8의 갯수를 찾아 모두 더합니다.
따라서 맨 앞자리가 8인 경우가 예외가 되는데, 어차피 n-1자리는 재귀 호출로 구해지니까 맨 앞자리가 몇번 있는지만 알면 됩니다.
예를 들어 84562인 경우 8이 맨 앞자리인 수는 4562번 나타나기 때문에 뒷자리를 더해 주도록 했습니다.
9인 경우는 10000번 나타나니까 이걸 더해줬구요
한자리인 경우는 지수가 -1이 되기 때문에 예외처리 해줬습니다.
python 3.9.1
/* 1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함) */
let count = 0
for (let i = 1; i <= 10000; i++) {
for (let j = 0; j < String(i).length; j++) {
String(i)[j] === "8" && count++
}
}
console.log(count)
count = 0 # 8의 개수 0개로 시작
for x in range(1,10000): # 1~10000까지 반복
for i in str(x): # 해당 숫자를 문자열로 반환 , (Ex, 1234 이면 '1234'로 for문에 들어가면 '1','2','3','4' 로 반복)
if i == '8': # 문자열로 반환된 숫자가 8이면
count+=1 # 1개를 카운트해라
else:
continue # 없으면 다시 반복문
count
(java)
int count = 0;
int sum = 0;
for (int i = 1; i <= 10000; i++) {
if (i % 10 == 8)
count++;
if ((i / 10) % 10 == 8)
count++;
if ((i / 100) % 10 == 8)
count++;
if (i / 1000 == 8)
count++;
sum = count;
}
System.out.println("sum : " + sum)
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int cnt=0;
for(int i=1; i<10001; i++)
{
for(int j=0; j<5; j++)
{
if ((int)(i/pow(10,j))%10==8)
cnt++;
}
}
cout<<cnt<<endl;
return 0;
}
C++시작한 코린이입니다...
c로 풀었읍니다~```
int main(void) {
int i, cont, a, b, c, d;
cont = 0;
for(a=0; a<=9; a++){
for(b=0; b<=9; b++){
for(c=0; c<=9; c++){
for(d=0; d<=9; d++){
if(d == 8){
cont += 1;
}
if(c == 8){
cont += 1;
}
if(b == 8){
cont += 1;
}
if(a == 8){
cont += 1;
}
}
}
}
}
printf("%d", cont);
} ```
먼가 위의 넥슨 입사문제랑 비슷해서 빠르게 풀엇네영
사실 사고력을 요하는 문제이지만
결국 컴퓨터로 노가다 돌린거랑 마찬가지라... 부끄럽습니다.
#include <stdio.h> //printf
#include <math.h> //pow
int i, t, y, result;
void find8(int x);
int main()
{
for (i = 1; i < 10000; i++)
find8(i);
printf("8의 개수 : %d", result);
return 0;
}
void find8(int x) {
for (t = 0; t < 4; t++) {
y = (x % (10 * (int)pow(10, t))) / (1 * (int)pow(10, t)); // (X % 10) / 1 = 일의 자리수, (X % 100) / 10 = 십의 자리수
if (y == 8) //해당 자리수가 8이면 result + 1
result += 1;
}
}
C를 이용해 작성했습니다. 아래는 입력받은 수까지 8의 개수를 구할 수 있도록 작성했습니다.
#include <stdio.h> //printf
#include <math.h> //pow
int i, t, cnt, result;
int n, x, y;
void find8(int x, int y);
int main()
{
printf("1이상의 수를 입력해 주세요 : "); // 정수 입력
scanf_s("%d", &n);
i = n; // 입력받은 정수의 자릿수 구하기
while (i > 0) {
i /= 10;
++y;
}
for (i = 1; i < n; i++)
find8(i, y);
printf("8의 개수 : %d", result);
return 0;
}
void find8(int x, int y) {
for (t = 0; t <+ y; t++) {
cnt = (x % (10 * (int)pow(10, t))) / (1 * (int)pow(10, t)); // (X % 10) / 1 = 일의 자리수, (X % 100) / 10 = 십의 자리수
if (cnt == 8) //해당 자리수가 8이면 result + 1
result += 1;
}
}
count = 0
for i in range(1, 10000):
if "8" in str(i):
for j in str(i):
if int(j) == 8:
count += 1
print(count)
<파이썬 3>
[결과] 4000
int totalCount = 0;
for(int i=1; i<=10000; i++) {
String number = Integer.toString(i);
String[] strArray = number.split("");
//8이포함될경우
for(String s : strArray) {
if(s.equals("8")) {
totalCount++;
}
}
}
System.out.println(totalCount);
def count8(start,end,search_no):
buf=""
for i in range(int(start),int(end)+1):
buf=buf+str(i)
return buf.count(str(search_no))
count8(1,10000,8)
str_Num = [int(x) for i in range(10001) for x in str(i) ]
print(f'8의 개수는 ', str_Num.count(8), '개 입니다.')
public class problem1 {
public static void main(String[] args) {
int count = 0;
int[] arrays01 = new int[5];
for (int i = 0; i < 10; i++) {
arrays01[1] = i;
for(int j = 0; j < 10; j++) {
arrays01[2] = j;
for(int k = 0; k < 10; k++) {
arrays01[3] = k;
for(int l = 0; l<10; l++) {
arrays01[4] = l;
for(int i2 = 1; i2<5; i2++) {
if(arrays01[i2] == 8) {
count += 1;
}
}
}
}
}
}
System.out.println(count);
public class CountingEight { public static void main(String[] args) { for (int i=0; i<=10000; i++){ searchEight(i); } System.out.println("1에서 10,000 사이에 존재하는 8의 개수는? "+count); } private static int count = 0; public static void searchEight(int num){ if (num%10==8) count++; if (num>10) searchEight(num/10); } }
%%timeit str(list(range(1, 10001).count('8') ===== count = 0 for i in range(10001): if '8' in str(i): count += stri(i).count('8') count ==== str([i for i in range(10001]).count('8')
count=0
for i in range(1,10001):
for j in range(len(str(i))):
if str(i)[j]=='8':
count+=1
print(count)
lst = []
eight = "8"
for i in range(1,10001):
for m in str(i):
if eight == m:
lst.append(int(m))
print(lst.count(8))
#codingdojing_google_count8
#1~9999 -> 999까지의 8의 숫자를 세고 8개수 * 10 + 1000(8000 대 숫자)
count = 0
for num in range(1,1000):
for i in str(num):
if i == '8': count += 1
print(count*10 + 1000)
###### 줄여보자
#생각해보니 각 자리수의 이 있는 경우, 0~999까지 총 1000개씩.. 따라서 1000개 * 4 = 4000개
print(str(list(range(1,10000))).count('8')) ## 내부값이 그냥 하나의 string 타입..
def count():
count = 0
for n in range(1, 10001):
for i in str(n):
if i == '8':
count += 1
print(count)
count()
eight = 0 for n in range(1,10001): n_list = list(map(int, str(n))) eight += n_list.count(8)
print(eight)
파이썬으로 작성하였습니다.
temp = []
for i in range(1,10000):
for j in str(i):
temp.append(int(j))
print(temp.count(8))
개선할 수 있도록 코드 리뷰 부탁드립니다.
package justStudying;
public class test1_20210818 {
public static int sol(int num) {
int ans = 0;
String numS = Integer.toString(num);
for(int i=0; i<numS.length(); i++) {
switch(numS.substring(i,i+1)) {
case "8":
ans++;
break;
default:
break;
}
}
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int ans = 0;
for(int i=1; i<=10000; i++) {
ans += sol(i);
}
System.out.println(ans);
}
}
def find_8():
cnt = 0
for i in range(1,10001):
cnt += str(i).count('8')
return cnt
if __name__ == '__main__':
print(find_8())
void main()
{
int sum = 0;
for (int i = 1; i <= 10000; i++)
{
char* ntos = new char[5];
sprintf(ntos, "%d", i);
int len = strlen(ntos);
for (int j = 0; j < len; j++)
{
sum += ntos[j] == '8' ? 1 : 0;
}
}
cout << sum;
}
mylist=[]
cnt=0
for i in range(1,10000):
for j in str(i):
if j=='8':
cnt+=1
mylist.append(cnt)
cnt=0
print(sum(mylist))
너무 단순하게 푼 것 같다...ㅜ.ㅜ
static void count8(int x) {
int count = 0;
for(int i = 1; i <= x; i++) {
for(int j = 0; j < (i+"").length(); j++) {
if((i+"").charAt(j) == '8')
++count;
}
}
System.out.println(count);
}
public static void main(String[] args) {
count8(10000);
}
var result = 0;
for(var i = 1; i <= 10000; i++) {
var eight = i.toString();
if(eight.indexOf(8) > -1) {
for(var j = 0; j <= eight.length; j++) {
if(parseInt(eight[j]) == 8) {
result ++;
}
}
}
}
var count = 0;
for(i=1; i<=10000; i++) {
var arr = i.toString().split("")
for(j=0; j<arr.length; j++) {
if(arr[j] === "8") count++
}
}
console.log(count)
public class Main {
public static void main(String[] args) {
int ans = 0;
for(int i=0;i<10000;i++){
int copy = i;
while (copy != 0)
{
if(copy % 10 == 8 ) ans++;
copy /= 10;
}
}
System.out.println(ans);
}
}
n8 = 0
for i in range(1,10001) :
arr = list(map(int,"".join(str(i))))
if 8 in arr :
n8 += arr.count(8)
print(n8)
numbers = []
for x in range(1, 10001):
numbers.append(x)
numbers_total = ["".join(map(str,numbers))]
print("8이 몇번 들어가니?: ", numbers_total[0].count('8'))
# 한줄로 해버리깅~~
a = "".join(str(x) for x in range(1, 11)).count('8')
print(a)
class Total8
{
public static void main(String [] args)
{
int count=0;
for(int i=1; i<10001; i++)
{
if(i/1000 ==8) // 천의 자리
count++;
if((i/100)%10 == 8) // 백의 자리
count++;
if((i/10)%10 ==8) // 십의 자리
count++;
if(i%10 ==8)// 일의 자리
count++;
}
System.out.println("8의 총 개수 : "+ count);
}
}
count_8 = 0
for num in range(1,10000):
for num_str in str(num):
if '8' == num_str:
count_8 += 1
print(count_8)
count=0
def counting(i):
for i in str(i):
if i=="8":
global count
count+=1
for i in range(1,10001):
counting(i)
print(count)
eight = 0
for i in range(1, 10001):
i = str(i)
for item in range(len(i)):
if '8' in i[item]:
eight += 1
print(eight)
package org.javaturotials.ex; import java.util.*;
public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count=0; for(int i=1; i<10000; i++) { String a = String.valueOf(i); String[] arr = new String[a.length()]; arr=a.split(""); for(int j=0; j<arr.length; j++ ) { if(Integer.valueOf(arr[j])==8) { count++; } } } System.out.println(count); } }
package org.javaturotials.ex; import java.util.*;
public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count=0; for(int i=1; i<10000; i++) { String a = String.valueOf(i); String[] arr = new String[a.length()]; arr=a.split(""); for(int j=0; j<arr.length; j++ ) { if(Integer.valueOf(arr[j])==8) { count++; } } } System.out.println(count); } }```{.java} package org.javaturotials.ex; import java.util.*;
public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count=0; for(int i=1; i<10000; i++) { String a = String.valueOf(i); String[] arr = new String[a.length()]; arr=a.split(""); for(int j=0; j<arr.length; j++ ) { if(Integer.valueOf(arr[j])==8) { count++; } } } System.out.println(count); } } ```
def count_8(a):
count8=0
for s in str(a):
if s=='8':
count8+=1
return count8
print(count_8(8088))
sum=0
for i in range(1,10001):
sum+=count_8(i)
print(sum)
4000
#include <iostream>
int main() {
int count = 0, i = 1;
while (i <= 10000) {
int n = i;
while (n != 0) {
if (n % 10 == 8) count++;
n /= 10;
}
i++;
}
std::cout << count;
}
쉽게 생각하면, 0000~9999까지 각 자리수마다 0~9까지 가능한 것이니, 0~9까지 숫자가 모두 동일한 갯수 만큼 나온다는 것을 알 수있습니다.
그럼 총 10,000가지 숫자가 각각 4자리 이기 때문에 전체 들어가는 숫자의 갯수는 4만개가 되고, 이를 10으로 나누면, 4000이 됩니다.
def to_count_num(num, max_num):
num_mat = [int(k) for i in range(1, max_num + 1)
for k in str(i)]
return num_mat.count(num)
num = input('카운팅하기를 원하는 숫자가 무엇입니까? : ')
max_num = input('숫자 범위의 최대값을 입력해주세요. : ')
print('1 ~ ' + max_num + ' 범위에서 숫자 ' + num + '의 개수는 ' + str(to_count_num(int(num), int(max_num))) + '개 입니다.')
lst = [str(i) for i in range(1,10001)]
count = 0
for i in lst:
if '8' in i:
eight = i.count('8')
count += eight
print(count)
count = 0
for num in range(1, 10001):
if '8' in str(num):
for digit in str(num):
if digit == '8':
count += 1
print(count)
print(sum([str(x).count(str(8)) for x in range(0,10000)]))
결과값: 4000
다양한 접근이 가능하다는 걸 배우는 것 같습니다. 감사합니다~
print(dic[8]){.python}
dic={i:0 for i in range(10)}
print(dic)
for i in range(10000):
for j in str(i):
dic[int(j)]+=1
print(dic[8])
print(count){.python}
count=0
for i in range(1,10001):
for j in str(i):
if j=='8':
count+=1
print(count)
i = 0
num = 0
for i in range(10001):
for tp in str(i):
if tp == '8':
num += 1
print("Total number of 8 is " + str(num))
자바로 풀어보았습니다.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> digits = new ArrayList<>();
int n, i=1, count8=0;
while(true) {
System.out.println("자연수 n을 입력하시오:");
n = scan.nextInt();
if(n<1) {
System.out.println("잘못 입력하셨습니다.\n");
}else {
break;
}
}
while(i<=n) {
int j=i;
while(j>0) {
digits.add(j%10);
j /= 10;
}
for(j=0;j<digits.size();j++) {
if(digits.get(j)==8) {
count8+=1;
}
}
digits.clear();
i++;
}
System.out.println(String.format("1부터 %d까지 8이라는 숫자는 %d번 나옵니다. \n", n, count8));
}
}
count=0
for i in range(10001):
for num in list(str(i)):
if num=="8":
count+=1
print(count)
4000 나왔습니다. 한줄로도 할수있었네요ㄷㄷㄷ
num_list = [ ','.join(str(i)).split(',') for i in range(1,10001) ]
num_sum =sum(num_list, [])
num_sum.count(str(8))
파이썬입니당
벽에 0000부터 9999까지 적어본다고 가정하면 수 하나에 4개의 숫자가 있고 수가 총 만개이므로 4만개의 숫자가 있고 0부터 9까지 같은비율이니 4만을 10으로 나누면 4천개 ! 그러므로 4천개
번외로 8 자체를 포함하지 않는 수의 갯수는 6561 이다! 이는 □□□□ 각 네모가 자릿수라고 생각하면 각 네모에는 8을 제외한 0,1,2,3 4,5,6,7,9 인 9가지의 숫자가 들어갈수 있기때문에 9^4 인 6561이 된다.
# 0부터 9999까지 8이 안들어가는 수 개수
alist = []
cc = 0
for ii in range(10000):
c = 0
for i in str(ii):
if i == '8':
c = 1
if c == 0:
cc += 1
print(cc)
num_8 = 0
for num in range(1, 10001): #num = 1~10000까지의 숫자를 의미
number = list(map(int, str(num)))
result = number.count(8) #number 리스트 안에 8의 갯수를 파악
num_8 += result #8의 숫자만큼 합산
print(num_8)
su = 0
for i in range(1,10001): i = str(i)
for j in i:
if j == "8":
su += 1
else:
continue
print(su)
import java.util.Scanner;
public class Problem3 {
static void numberCounter(int n, int m) {
StringBuilder line_has_m = new StringBuilder();
StringBuilder line_nhas_m = new StringBuilder();
for (int i=1; i<n+1; i++) {
line_has_m.append(i);
}
String x = line_has_m.toString(); //세고자 하는 숫자 m이 표함된 숫자열
String[] temp = x.split(String.valueOf(m));
for (String s : temp) {
line_nhas_m.append(s);
}
String y = line_nhas_m.toString(); //세고자 하는 숫자 m이 제거된 숫자열
System.out.println("정답: "+(x.length()-y.length())+" 개 입니다.");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("1부터 몇까지? -> ");
int num1 = sc.nextInt();
System.out.print("세고 싶은 숫자는? -> ");
int num2 = sc.nextInt();
numberCounter(num1, num2);
}
}
total=[]
for i in range(1,10000):
temp_num=[int(a) for a in str(i)]
total=total+temp_num
num_of_8=total.count(8)
print(num_of_8)
def counter8(x=0,y=10):
count1=0
for a in range(x,y):
for b in str(a) :
if b == '8' : count1 += 1
print(count1)
counter8(1,10000)
count8 = {8:0}
for i in range (1,10001):
for x in str(i):
if int(x) == 8:
count8[8] +=1
print (count8)
public class Q3 {
public static void main(String[] args) {
int count=0;
for(int i=1;i<=10000;i++) {
for(int j=0;j<Integer.toString(i).length();j++) {
if(Integer.toString(i).charAt(j)=='8') {
count++;
}
}
}
System.out.println(count);
}
}
count = 0
for i in range(10000):
a = str(i)
if '8' in a:
for j in range(len(a)):
if a[j] == '8':
count += 1
print(count)
let count = 0;
let str;
for (let i = 1; i < 10001; i++) {
str = String(i);
for (let j = 0; j < str.length; j++) {
if (str[j] === '8') {
count += 1;
}
}
}
print(sum([len([x for x in str(i) if x == '8']) for i in range(1, 10000)]));
python 3.10.8 리스트 내포 스타일
파이썬입니다.
count8 = 0
for i in range(10001) :
for j in str(i) :
if j == "8" :
count8 += 1
print(count8)
Python. 정답은 4000. 습관적으로 for 반복문을 사용했는데, 리스트를 전무 문자열로 바꾼 다음에 개수를 세는 방법도 있군요..! 다들 대단...!
eight_sum=0
for i in range (1, 10001):
a=str(i) #int인 i를 문자열(str)로 전환
b=a.count('8') #count 함수로 문자열 내 8의 개수 확인
eight_sum+=b
print(eight_sum)
cnt = 0
for i in range(10000):
for j in range(len(str(i))):
if int((str(i))[j]) == 8:
cnt += 1
print(cnt)
python
const checkEight = (number) => {
let answer = 0
for(let i = 1; i <= number; i++){
let numToStr = String(i)
let numArr = Array.from(numToStr)
if(numArr.includes('8')){
for(let i of numArr){
if(i === '8'){
answer++
}
}
}else continue
}
return answer
}
input을 10,000으로 받고, check8이라는 배열을 생성합니다. fill을 사용해 모두 0으로 채워 넣은 후, map을 활용해 index값으로 늘리면서 10,000까지 들어 있는 배열을 만들었습니다.
이후 문자열로 변환 후 모든 숫자를 split("")하였습니다. 이후 filter를 사용해 "8" 값을 찾아냈고 길이만큼 출력했습니다. (숫자는 split("")을 할 수 없습니다.)
let input = 10000;
let check8 = Array(input).fill(0).map((v, i) => i);
let result = check8.toString().split("").filter((v) => v === "8").length;
console.log(result);
print(''.join(map(str, [i for i in range(1, 10001)])).count("8"))
>>> 4000
풀고보니 쓸데없이 리스트 컴프리헨션을 썼네요.^^;
count = 0
for i in range(1, 10000):
if i < 10 and i % 8 == 0:
count += 1
elif i < 100:
if i // 10 == 8:
count += 1
if i % 10 == 8:
count += 1
elif i < 1000:
if i // 100 == 8:
count += 1
if (i % 100) // 10 == 8:
count += 1
if i % 10 == 8:
count += 1
else:
if i // 1000 == 8:
count += 1
if (i % 1000) // 100 == 8:
count += 1
if (i % 100) // 10 == 8:
count += 1
if i % 10 == 8:
count += 1
print(count)
max_len = 10000
count = 0
for i in range(max_len):
for i in str(i):
if i == '8':
count += 1
print(count)
#str로 변환하여 추출하면 더 빠를 것 같다고 생각했습니다
counting = 0
for n in range(1, 10001):
new = str(n)
for i in new:
if i == "8":
counting += 1
print(counting)
def count_eight(number):
count = 0
for idx in str(number):
if idx == "8":
count += 1
return count
count_list = []
for idx in range(10000):
count_list.append(count_eight(idx))
print(sum(count_list))
파이썬으로 푼 예시답변 입니다. 그냥 전부 리스트로 만든 다음 숫자를 각각 분리해서 '8'이 몇번 있는지 세줍니다. (count 사용) 그리고 sum2에 넣어서 끝냅니다.
sum2 = 0
for i in range(1, 10001):
k = list(str(i)).count('8')
sum2 += k
print(sum2)
function solution(number) { let answer = 0; for (let i=0; i< number; i++) { answer += ([...String(i)].filter(v => v === '8').length); // console.log([...String(i)], [...String(i)].filter(v => v === '8').length); } return answer; }
console.log(solution(10000));
num = 0
for i in range(10001):
str_i = str(i)
for character in str_i:
if character == '8':
num+=1
print(num)
element = []
count = 0
total_list = list(range(1,10000))
for i in str(total_list):
for j in str(i):element.append(j)
count = element.count("8")
print(count)
n = 10000
cnt = 0
for i in range(10000):
nLst = list(str(i))
if '8' in nLst:
cnt += nLst.count('8')
print(cnt)
javascript 풀이입니다.
const answer = Array(10000).fill(0).map((v,i)=>i).join("").split("").filter(v=> v==='8');
rerturn answer.length;
max_number = 10000 count_eight = 0
for i in range(1, max_number +1): j = i while True: temp_number = j % 10 if temp_number == 8: count_eight += 1 if j // 10 == 0: break j = j // 10
print(count_eight)
let totCnt = 0; for(let i=1; i<10000; i++){ let item = i+''; for(let j=0; j<item.length; j++){ if(item.charAt(j) == '8'){ totCnt++; } } } console.log("1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가? : " , totCnt);
eight_count=0
for a in range(1,10001):
number=str(a).count('8')
eight_count+=number
number=0
print(eight_count)
def count(num):
count = 0
if '8' in str(num):
for i in str(num):
if i == '8':
count += 1
return count
total = 0
for i in range(1, 10001):
total += count(i)
print(total)
cuantos_ocho = 0
for i in range(1, 10001):
str_i = str(i)
cuantos_ocho += str_i.count('8')
print(cuantos_ocho)
```{.java}
```public static void main(String[] args) {
int max = 10000;
int addResult = 0;
int[] intResult = new int[5];
for (int a = 1; a <= max; a++) {
String inputString = String.valueOf(a);
String[] result = inputString.split("");
for (int i = 0; i <result.length; i++) {
intResult[i] = Integer.parseInt(result[i]);
if (intResult[i] == 8) {
addResult = addResult + 1;
}
}
}
System.out.println("8 의 수 : " + addResult);
}
count = 0
list_num = []
for i in range(0, 10000): # 55
list_num = list(str(i))
print(list_num)
for j in list_num:
if '8' in j:
count += 1
print(f"1부터 10,000까지 8이라는 숫자가 총 {count}만큼 나온다.")
eight_num = 0
for n in range(1, 10000+1):
n_str = str(n)
eight_num += n_str.count('8')
print(eight_num)
# 1개의 8이 있을 경우: 예) XXX8(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 1개 할당하는 경우의 수는 조합으로 구함: C(4, 1) = 4!/1!(4-1)! = 4
# 경우의 수 x 9 x 9 x 9 x 8의 개수: 4 x 9 x 9 x 9 x 1 = 2916
# 2개의 8이 있을 경우: 예) XX88(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 2개 할당하는 경우의 수는 조합으로 구함: C(4, 2) = 4!/2!(4-2)! = 6
# 경우의 수 x 9 x 9 x 8의 개수: 6 x 9 x 9 x 2 = 972
# 3개의 8이 있을 경우: 예) X888(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 3개 할당하는 경우의 수는 조합으로 구함: C(4, 3) = 4!/3!(4-3)! = 4
# 경우의 수 x 9 x 8의 개수: 4 x 9 x 3 = 108
# 4개의 8이 있을 경우: 예) 8888(* X는 8을 제외한 0 ~ 9까지의 숫자가 가능. 결국 9가지 방법이 가능)
# 4개의 자리에 8을 4개 할당하는 경우의 수는 조합으로 구함: C(4, 4) = 4!/4!(4-4)! = 1
# 경우의 수 x 1 x 8의 개수: 1 x 1 x 4 = 4
import math
total = 0
for n in range(1, 5): # n: 8의 개수, 8이 없는 자리수: 4 - n
cnt = math.comb(4, n)
sum = cnt * 9**(4-n) * n
total += sum
print("total = ", total)
JAVA입니다.
package 구글_입사문제_중에서;
public class Main {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 10000; i++) {
String numStr = Integer.toString(i);
for (Character c : numStr.toCharArray()) {
if (c == '8') {
count++;
}
}
}
System.out.println(count);
}
}
'''
1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※ 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
'''
def examineNumber(repeat, num):
total = 0
for i in range(1, repeat + 1):
total += str(i).count(str(num)) # 문자열 변환 후 count() 사용
return total # return으로 값 반환
# 실행
print(examineNumber(10000, 8))
#repeat = int(input("찾을 범위 입력 : "))
#num = int(input("찾을 숫자 입력 : "))
#examineNumber(repeat,num)
eight_cnt = 0
for i in range(10000):
eight_cnt += str(i).count("8")
print(eight_cnt)
이미 print(str(list(range(10001)).count("8"))이 올라와 있어서 풀어서 하는 방법
int cnt = 0;
for(int i = 1; i <= 10000; i++) {
String numStr = String.valueOf(i);
for(char c : numStr.toCharArray()) {
if( c == '8') {
cnt++;
}
}
}
출력 4000
count_8 = 0
for i in range(1, 10001):
count_8 += str(i).count('8')
print(f"total: {count_8}")
파이썬 공부시작한 뉴비입니다 4000!