1부터 10,000까지 8이라는 숫자가 총 몇번 나오는가?
8이 포함되어 있는 숫자의 갯수를 카운팅 하는 것이 아니라 8이라는 숫자를 모두 카운팅 해야 한다.
(※(注記) 예를들어 8808은 3, 8888은 4로 카운팅 해야 함)
//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
2014年05月30日 18:11
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))
2014年06月19日 16:25
정답은 4000개입니다
cnt = 0
for i in range(1,10000):
for j in str(i):
if j is '8':
cnt += 1
print cnt
2014年07月01日 15:44
길이는 길지만, 하나하나 루프 돌리면서 개수를 세는 것보다는 훨씬 빠르게, 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 + "개");
2014年08月13日 16:06
1~10000범위의 숫자를 문자열, 즉 str로 하여금 싱글쿼터 안에 8을 넣음으로써 문자열으로 인식하여 8의 갯수를 카운트 합니다.
>>> print str(range(1, 10000)).count('8')
4000
2014年08月16日 22:33
풀이 작성