結果
問題 | No.518 ローマ数字の和 |
ユーザー |
![]() |
提出日時 | 2021-01-19 16:30:16 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 144 ms / 2,000 ms |
コード長 | 2,545 bytes |
コンパイル時間 | 2,587 ms |
コンパイル使用メモリ | 78,540 KB |
実行使用メモリ | 55,984 KB |
最終ジャッジ日時 | 2024-12-17 12:50:29 |
合計ジャッジ時間 | 6,549 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 19 |
ソースコード
import java.util.*;public class Main {static final int[] NUM = new int[]{1, 5, 10, 50, 100, 500, 1000};static final char[] ROMAN = new char[]{'I', 'V', 'X', 'L', 'C', 'D', 'M'};public static void main (String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int ans = 0;for (int i = 0; i < n; i++) {ans += getNum(sc.next());}if (ans > 3999) {System.out.println("ERROR");} else {System.out.println(getRoman(ans));}}static String getRoman(int x) {StringBuilder ans = new StringBuilder();if (x >= 1000) {int count = x / 1000;for (int i = 0; i < count; i++) {ans.append("M");}x %= 1000;}if (x >= 100) {int count = x / 100;if (count == 9) {ans.append("CM");count = 0;} else if (count == 4) {ans.append("CD");count = 0;} else if (count >= 5) {ans.append("D");count -= 5;}for (int i = 0; i < count; i++) {ans.append("C");}x %= 100;}if (x >= 10) {int count = x / 10;if (count == 9) {ans.append("XC");count = 0;} else if (count == 4) {ans.append("XL");count = 0;} else if (count >= 5) {ans.append("L");count -= 5;}for (int i = 0; i < count; i++) {ans.append("X");}x %= 10;}if (x >= 1) {int count = x;if (count == 9) {ans.append("IX");count = 0;} else if (count == 4) {ans.append("IV");count = 0;} else if (count >= 5) {ans.append("V");count -= 5;}for (int i = 0; i < count; i++) {ans.append("I");}}return ans.toString();}static int getNum(String s) {int stock = 0;int ans = 0;for (char c : s.toCharArray()) {int x = getRomanToNum(c);if (stock < x) {stock = x - stock;} else {ans += stock;stock = x;}}ans += stock;return ans;}static int getRomanToNum(char c) {for (int i = 0; i < NUM.length; i++) {if (c == ROMAN[i]) {return NUM[i];}}return 0;}}