• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

N進数変換

date: 2021-05-02 excerpt: decimal to any base(10進数を任意のN進数に変換)について

tag: algorithmmathinteger


decimal to any base(10進数を任意のN進数に変換)について

10進数を任意のN進数のリストに変換する

def decimal_to_base(x: int, base: int) -> list:
    if x//base:
        return decimal_to_base(x//base, base) + [x%base]
    return [x%base]
 
x = decimal_to_base(10, 2)
assert x == [1, 0, 1, 0]
x = decimal_to_base(10, 8)
assert x == [1, 2]
x = decimal_to_base(10, 16)
assert x == [10]
  • colab

10進数を任意のN進数の記号のリストに変換する

# 文字の対応表
m = {}
for i in range(100):
    if i >= 10:
        m[i] = chr(ord('A')+i-10)
    else:
        m[i] = str(i)
        
def decimal_to_base_str(x: int, base: int) -> list:
    to_str = lambda a: m[a]
    if x//base:
        return decimal_to_base_str(x//base, base) + [to_str(x%base)]
    return [to_str(x%base)]
 
x = decimal_to_base_str(111111, 16)
assert x == ['1', 'B', '2', '0', '7']

数字列をn進数として解釈する

def anybase_to_decimal(x: "List[str]", k: int):
    '''
    x: n進数数字
    k: 変換元とする進数
    '''
    dec = 0
    for idx, ch in enumerate(reversed(x)):
        dec += int(ch, k) * (k**idx)
    return dec

# 11b -> 16**2 + 16*1 + 11 -> 283
anybase_to_decimal(list("11b"), 16)
  • colab

例; 負の基底の-2進数に変換する

問題

  • AtCoder Beginner Contest 105; C - Base -2 Numbe

解説

  • 負の基底を使うときは入力を反転させる

解答

N=int(input())
 
def decimal_to_base(x: int, base: int) -> list:
    if x//base:
        return decimal_to_base(x//base, base) + [x%base]
    return [x%base]
 
arr = decimal_to_base(-1 * N, -2)
print(*[abs(x) for x in arr], sep="")


algorithmmathinteger Share Tweet