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?

数式の計算(多桁)

Posted at

一桁だと動いたコードが、多桁になった瞬間に崩壊。やっぱり文字列処理、奥深い!


🧪 問題概要

文字列で渡される数式(演算子は +- のみ)を計算して、結果を出力せよ。

入力例:

781781+272-178781+3919-1737389

出力例:

-1130198


💥 NGコード例

const chars = Array.from(input); // 一文字ずつバラされる

こうすると、例 "781"["7", "8", "1"] にバラバラ…。
前回の一桁問題と同じようにやって失敗(´;ω;`)



✅ OKコード(正規表現で意味ごと抽出)

const numbers = input.match(/\d+/g).map(Number);
const operators = input.match(/[+-]/g);

let result = numbers[0];
for (let i = 0; i < operators.length; i++) {
  result = operators[i] === "+" ? result + numbers[i + 1] : result - numbers[i + 1];
}

🔍 解説

  • \d+ :連続する数字 → 多桁でも1つの塊に
  • [+-]+- のどちらか → 記号だけ抽出
  • .match() :文字列を「意味単位」で切り分けられる超便利メソッド!
  • g :global(全体) → 該当するすべてを対象に抽出!



☝️ 技術ポイントまとめ

  • 数字と記号をロジック的に分離するには「正規表現 + match()」をつかう
  • 特に多桁対応では \d+ が便利
  • split()Array.from() では構造を失うリスクあり




僕の失敗談と解決話!

1
0
1

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?