2
2

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 1 year has passed since last update.

[c++]n進法からm進法への基数変換

Last updated at Posted at 2023-03-10

はじめに

正の整数(n進法)をm進法に変換。そのメモ。競プロ用。

ソースコード(c++)

#include <bits/stdc++.h>
using namespace std;

void ntom(const string str, const int n, const int m, string &res) {
    unsigned long sum = 0;
    for (char c : str) {
        sum = sum * n + (c - '0');
    }
    res = "";
    do {
        int num = sum % m;
        res = static_cast<char>(num + '0') + res;
        sum /= m;
    } while (sum);
}

説明

n進法 -> m進法

  1. n進法の数値を文字列(str)で表す

  2. strにおけるi桁目の数値をn^(i - 1)乗で重み付けしたものをsumに足す
    ※ 347(8)の場合
    sum(10) = 3 * 8 ^ 2 + 4 * 8 ^ 1 + 7 * 8 ^ 0
    = 3 * 64 + 4 * 8 + 7
    = 231(10)

  3. sumをmで割った余りを、新たな文字列(res)に足し合わせる

  4. sumが0になるまで 3.をループ

使用例

ソースコード

#include <bits/stdc++.h>
using namespace std;

void ntom(const string str, const int n, const int m, string &res) {
    unsigned long sum = 0;
    for (char c : str) {
        sum = sum * n + (c - '0');
    }
    res = "";
    do {
        int num = sum % m;
        res = static_cast<char>(num + '0') + res;
        sum /= m;
    } while (sum);
}

int main(void) {
    string s = "21";
    const int n = 8, m = 9; // n進数 -> m進数
    string res;
    ntom(s, n, m, res);
    cout << s << ' ' << res << '\n';
    return 0;
}

出力

21 18

関連問題

競プロ典型90問 067 - Base 8 to 9(★2)

2
2
2

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?