문제 링크

문제 요약

  • 주어진 진법 x (2 이상 36 이하)로 표현된 숫자 z를 진법 y (2 이상 36 이하)로 변환하는 문제입니다.
  • 숫자의 각 자리는 0부터 9까지는 그대로, 10부터 35까지는 A부터 Z까지의 대문자로 표현됩니다. 숫자 z는 40억을 넘지 않습니다.

풀이

이 문제는 임의의 진법에서 다른 임의의 진법으로 숫자를 변환하는 전형적인 진법 변환 문제 유형 입니다. 이러한 진법 변환은 보통 두 단계로 나누어 수행합니다:

  1. 원래 진법 (Base X)의 숫자를 10진수로 변환합니다.
  2. 10진수로 변환된 숫자를 목표 진법 (Base Y)으로 변환합니다.

이 두 단계를 아래 코드에서는 x_to_y_base 함수 안에 구현되어 있습니다.

정답 코드

def num(c):
  if c.isdigit():
    return int(c)
  return ord(c) - ord('A') + 10
 
 
def num_to_char(n):
  if n < 10:
    return str(n)
  return chr(n - 10 + ord('A'))
 
 
def x_to_y_base(x, y, n):
  result = 0
 
  n1 = reversed(n)
 
  crt = 1
  for i in n1:
    result += num(i) * crt
    crt *= x
  
  result_str = ""
  while result > 0:
    result_str = num_to_char(result % y) + result_str
    result //= y
  
  if result_str == "":
    result_str = "0"
  
  return result_str
 
 
def solve():
  a, b, k = input().split()
  a = int(a)
  b = int(b)
 
  print(x_to_y_base(a, b, k))
 
 
if __name__ == "__main__":
  tc = ii()
  for t in range(1, tc+1):
    ret = solve()
 

연관 페이지

참고 문헌 / 사이트