9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】n進数→10進数、10進数→n進数【AtCoder】

Last updated at Posted at 2021-02-20

ABC192
D - Base n
ででてきた、n進数⇄10進数 変換問題

今後のためにも、

  • n進数→10進数
  • 10進数→n進数

の自作ライブラリを作成を作っておく。


###(2021/02/24 追記)自作ライブラリ修正

  • 10進数→n進数のバグを修正
    • 余りが10以上になる場合の考慮漏れ
  • 引数・戻り値共にわかりやすいように int に統一
test.py
print(base_n(969,31)) #108
print(base_n(970,31)) #109
print(base_n(971,31)) #-1
print(base_n(991,31)) #-1
print(base_n(992,31)) #110
print(base_n(993,31)) #111

###ちなみに
Python標準で、n進数→10進数は以下のようにも記述できる。
しかし、intの第二引数はまさかの「36」までしか対応していない!
ABC192Dのような、n>36となりうる問題は解けないことに注意!

test.py
print(int('1111',2))
#15
print(int('1111',37))
#ValueError: int() base must be >= 2 and <= 36, or 0

#n進数→10進数

test.py
def base_10(num_n,n):
    num_10 = 0
    for s in str(num_n):
        num_10 *= n
        num_10 += int(s)
    return num_10

#10進数→n進数

test.py
def base_n(num_10,n):
    str_n = ''
    while num_10:
        if num_10%n>=10:
            return -1
        str_n += str(num_10%n)
        num_10 //= n
    return int(str_n[::-1])

###おまけ(練習問題)
ぜひ解いてみましょう!
C - N進数

おわり!

9
6
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
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?