1
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?

10 進数から M 進数に変換

Posted at

前回に引き続き、進数の変換問題!2進数へ変換するコードを応用して10進数から何進数にでも変換できるようにできた!


問題概要

  • 10 進数で表された整数 N, M が与えられる。
  • N を M 進数に変換して出力する。

入力例:

10 2

出力例:

1010




✅OK例1:

const rl = require('readline').createInterface({input:process.stdin});


rl.once('line', (input) => {
    const [N, M] = input.split(' ').map(Number);
    
    
    const base = [];
    for(let temp = N; temp > 0; temp = Math.floor(temp / M)){
        base.push(temp % M);
    }
    
    console.log(base.reverse().join(''));
    
    rl.close();
});

→前回のコードを応用(2→ M)



✅OK例2:

const rl = require('readline').createInterface({input:process.stdin});


rl.once('line', (input) => {
    const [N, M] = input.split(' ').map(Number);
    
    console.log(N.toString(M));
    
    
    rl.close();
});

.toString(進数) で、その進数の文字列へ変換。



📝気づきメモ

  • M進数でも、2進数へ変換するときと同じで、
    ✅ Mで割り続ける
    ✅ 余りを記録する
    ✅ 逆順に並べる

 という方法で変換できるとわかった。

  • .toString(radix)で変換するのがすごい楽だった。

まとめ

進数変換は最初難しそうに見えるけど、変換方法がわかれば、そこまで難しいコードではない。あと、魔法の.toString() を使ってしまえばいい!




僕の失敗談(´;ω;`)と解決法🐈

1
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
1
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?