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?

padStart() でゼロ埋めをスマートに!

Posted at

paiza のゼロ埋め問題に挑戦したら、最初は if 文ゴリ押しでダサいコードに…。padStart() を知ったら、一発で解決した ので、その学びをメモ。


整数 n(0~999)が1つ入力されるので3桁にそろえて出力する処理 を考える。
入力例 → 9 45 123
出力例 → 009 045 123


❌ NGコード:if 文でゴリ押し

rl.on('line', (line) => {
    if (line.length === 3) {
        console.log(line);
    } else if (line.length === 2) {
        console.log("0" + line);
    } else {
        console.log("00" + line);
    }
    rl.close();
});

🚨 問題点
if の分岐が増えてコードが読みにくい
バグの原因になりやすい


✅ OKコード:padStart() で一発解決!

rl.question('', (line) => {
    console.log(line.padStart(3, '0'));
    rl.close();
});

✨ 改善ポイント
✅ padStart(3, '0') で たった1行で解決!
✅ rl.question() で 一回の入力を確実に処理!
✅ 可読性アップ&ミス減少!


📌 padStart() のポイント

不足分を指定の文字で埋める

console.log('9'.padStart(3, '0'));  // "009"
console.log('42'.padStart(3, '0')); // "042"

デフォルトは半角スペース

console.log('42'.padStart(5)); // "   42"

ターゲットの長さ以下なら何もしない

console.log('1234'.padStart(3, '0')); // "1234"


🔍 まとめ

最初は if 文ゴリ押しで書いてたけど、padStart() で一発解決!
「ゼロ埋め? → padStart() でOK!」って流れを覚えよう!🔥

※ちなみに、on('line',~)は複数行入力向けと聞いたので、.questionを使ったのですが、
 paizaの問題で.question()を使うと上手く処理されず正解になりません(´;ω;`)
 通過するためにon('line',~)の方を使いました。

僕の失敗談と解決話!

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