[Baekjoon] 1748번 수 이어 쓰기 1

Updated:

문제

1부터 N까지의 수를 이어서 쓰면 다음과 같이 새로운 하나의 수를 얻을 수 있다.

1234567891011121314151617181920212223…

이렇게 만들어진 새로운 수는 몇 자리 수일까? 이 수의 자릿수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N(1 ≤ N ≤ 100,000,000)이 주어진다.

출력

첫째 줄에 새로운 수의 자릿수를 출력한다.

예제

Example 1:

Input: 
120
Output: 
252

조건

시간 제한 : 0.15초

메모리 제한 : 128 MB

풀이과정

풀이 1

자릿수 계산하면서 감소하는 방식으로 구현

n = int(input())
ans = 0

while(n > 0):
    x = n
    cnt = 0
    # 자릿수 계산
    while(x > 0):
        x //= 10
        cnt += 1
    ans += cnt *(n - (10**(cnt-1) - 1))
    n -= (n - (10**(cnt-1) - 1))
print(ans)

풀이 2

1부터 증가시키면서 구현

n = int(input())
ans = 0
start = 1
length = 1
while start <= n:
    end = start*10 - 1
    if end > n:
        end = n
    ans += (end-start+1)*length
    start *= 10
    length += 1
print(ans)

Leave a comment