
어느 누군가가 타임머신을 타고 과거로 가서 숫자 0이 없는 수 체계를 전파했습니다. 역사가 바뀌어 이제 사람들의 의식 속엔 0이란 숫자가 사라졌습니다. 따라서, 현재의 수 체계는 1, 2, 3, ..., 8, 9, 11, 12, ...와 같이 0이 없게 바뀌었습니다.
0을 포함하지 않은 자연수 num이 매개변수로 주어질 때, 이 수에 1을 더한 수를 return 하도록 solution 함수를 완성해주세요.
자연수 num이 solution 함수의 매개변수로 주어집니다.
자연수 num에 1을 더한 수를 return 해주세요.
| num | return |
|---|---|
| 9949999 | 9951111 |
9,949,999에 1을 더하면 9,950,000이지만 0은 존재하지 않으므로 9,951,111이 됩니다.
#You may use import as below.
#import math
def solution(num):
# Write code here.
answer = 0
return answer
#The following is code to output testcase.
num = 9949999;
ret = solution(num)
#Press Run button to receive output.
print("Solution: return value of the function is", ret, ".")
이번엔
빈칸 채우기문제가 아니라 함수 전체를 작성하는 문제이다.
#You may use import as below.
#import math
def solution(num):
# Write code here.
num += 1 # 1을 더함
new_num = ''
for n in str(num):
new_num += '1' if n == '0' else n
answer = int(new_num)
return answer
#The following is code to output testcase.
num = 9949999;
ret = solution(num)
#Press Run button to receive output.
print("Solution: return value of the function is", ret, ".")
def solution(num):
# Write code here.
num += 1
digit = 1
while num // digit % 10 == 0:
num += digit
digit *=10
return num
#The following is code to output testcase.
num = 9949999;
ret = solution(num)
#Press Run button to receive output.
print("Solution: return value of the function is", ret, ".")
1로 바꾸기 (ex - 일의 자리, 십의 자리 ...)digit는 1, 10, 100 순으로 증가하며 num 변수가 갖는 값의 자리수가 갖는 숫자를 추출하기 위해 사용하는 변수이다.0인 것을 1로 변경한다.replace() 함수를 사용#You may use import as below.
#import math
def solution(num):
# Write code here.
answer = int(str(num + 1).replace('0', '1'))
return answer
#The following is code to output testcase.
num = 9949999;
ret = solution(num)
#Press Run button to receive output.
print("Solution: return value of the function is", ret, ".")
replace()메소드를 이용하여 '0'을 '1'로 바꾸고 그것을 다시 정수형으로 변환한다.일반적으로 파이썬은 여러 가지 기능이 많은 함수들이 많아 쉽게 코드를 작성할 수 있다.
다만, 짧은 코드라고 해서 효율적이진 않다.
시간복잡도를 중요하게 여기는 코딩테스트에서는 옳지 않은 접근 방법이 많다.
이로 인해, 만약 본인이 작성한 코드가 수행시간이 얼마나 걸리는지 확인하려고 할때 time 모듈의 time() 함수를 사용하여 프로그램 실행 시간을 측정하면 된다.
import time
start= time.time()
num = 9949999;
for i in range(10000000000):
answer=int(str(num+1).replace('0','1'))
end= time.time()
print(end-start)
>>> 0.0243
start= time.time()
num = 9949999;
num = num+1
digit = 1
for i in range(10000000000):
while num // digit % 10 == 0:
num+= digit
digit *= 10
end= time.time()
print(end-start)
>>> 0.0055
해당 두 개의 코드를 봐도 코드 1)이 조금 더 효율적이지 않을까? 라고 생각하게 된다.
다만, 출력한 시간을 보자.
반복문을 사용한 코드가 더 시간이 짧은 것을 알 수 있다.
이런 식으로 문자열의 index(), replace() 등과 같은 함수는 시간복잡도가 많이 걸린다.
이를 고려하여 코드를 작성해보면 시간 복잡도를 줄일 수 있다.