0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

M進数をN進数に変換 (Pyhton)

0
Last updated at Posted at 2026-02-08

少し詰まったので、メモとして残しておきます。

考え方

int で一度10進数に戻してからN進数への変換計算を行う。

def convert_base(m, a, n):
    decimal_val = int(str(a), m)

    if decimal_val == 0:
        return "0"

    res = ""
    while decimal_val > 0:
        res = str(decimal_val % n) + res
        decimal_val //= n

    return res

Atcoder 典型90問 067 - Base 8 to 9(★2)

#
# M進数をN進数に変換
#


def convert_base(m, a, n):
    decimal_val = int(str(a), m)

    if decimal_val == 0:
        return "0"

    res = ""
    while decimal_val > 0:
        res = str(decimal_val % n) + res
        decimal_val //= n

    return res


N, K = map(int, input().split())

for _ in range(K):
    # N は8進数なので9進数に変換する
    lst_base9 = list(map(str, convert_base(8, N, 9)))
    for i in range(len(lst_base9)):
        if lst_base9[i] == "8":
            lst_base9[i] = "5"
    N = int("".join(lst_base9))

print(N)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?