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?

ローマ数字変換ツール(ステップ表示と厳密バリデーション付き)

1
Posted at

作ったもの

Roman Numeralhttps://sen.ltd/portfolio/roman-numeral/

スクリーンショット

  • アラビア数字 ↔ ローマ数字(1 〜 3999)
  • ステップバイステップの計算過程
  • 厳密バリデーション(IIII や VV を拒否)
  • 年号ショートカット
  • 1 〜 100 の対応表

vanilla JS、ゼロ依存、ビルド不要node --test で 88 ケース。

貪欲法

const TABLE = [
  [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
  [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'],
  [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'],
];

減算形(CM, CD, XC, XL, IX, IV)もテーブルに含めることで、1990 → M + CM + XC が自動で出る。特別扱い不要。

3999 が上限

標準ローマ数字は MMMCMXCIX = 3999 まで。4000 以上は vinculum(文字の上の横棒、×1000)が必要で、現代表記ではほぼ使われない。

厳密バリデーション regex

/^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/
  • M{0,3}: 千の位(0-3 個)
  • (CM|CD|D?C{0,3}): 百の位、900 / 400 / 0-300 / 500-800
  • (XC|XL|L?X{0,3}): 十の位
  • (IX|IV|V?I{0,3}): 一の位

これで IIII, VV, IIX, LL, DD を全部弾ける。

ローマ数字 → アラビア

左から走査して「次の方が大きければ減算形」:

if (next > cur) result += next - cur; i++;
else result += cur;

MCMXCIV を順に見れば M(1000) + CM(900) + XC(90) + IV(4) = 1994。

シリーズ

100+ 公開ポートフォリオ シリーズの #88 です。

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?