結果
問題 | No.518 ローマ数字の和 |
ユーザー |
![]() |
提出日時 | 2020-06-10 17:33:30 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 134 ms / 2,000 ms |
コード長 | 2,288 bytes |
コンパイル時間 | 2,238 ms |
コンパイル使用メモリ | 84,472 KB |
実行使用メモリ | 41,512 KB |
最終ジャッジ日時 | 2024-06-23 09:11:32 |
合計ジャッジ時間 | 6,048 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 19 |
ソースコード
import java.util.*;public class Main {static HashMap<Character, Integer> romanToInteger = new HashMap<>();public static void main (String[] args) {Scanner sc = new Scanner(System.in);romanToInteger.put('I', 1);romanToInteger.put('V', 5);romanToInteger.put('X', 10);romanToInteger.put('L', 50);romanToInteger.put('C', 100);romanToInteger.put('D', 500);romanToInteger.put('M', 1000);int sum = 0;int n = sc.nextInt();for (int i = 0; i < n; i++) {sum += getInteger(sc.next());}if (sum >= 4000) {System.out.println("ERROR");return;}StringBuilder sb = new StringBuilder();int first = sum / 1000;for (int i = 0; i < first; i++) {sb.append("M");}int second = sum % 1000 / 100;if (second == 9) {sb.append("CM");} else if (second == 4) {sb.append("CD");} else {if (second >= 5) {second -= 5;sb.append("D");}for (int i = 0; i < second; i++) {sb.append("C");}}int third = sum % 100 / 10;if (third == 9) {sb.append("XC");} else if (third == 4) {sb.append("XL");} else {if (third >= 5) {third -= 5;sb.append("L");}for (int i = 0; i < third; i++) {sb.append("X");}}int forth = sum % 10;if (forth == 9) {sb.append("IX");} else if (forth == 4) {sb.append("IV");} else {if (forth >= 5) {forth -= 5;sb.append("V");}for (int i = 0; i < forth; i++) {sb.append("I");}}System.out.println(sb);}static int getInteger(String s) {ArrayDeque<Integer> stack = new ArrayDeque<>();for (char c : s.toCharArray()) {int x = romanToInteger.get(c);if (stack.size() > 0 && stack.peek() < x) {stack.push(x - stack.pop());} else {stack.push(x);}}int ans = 0;while (stack.size() > 0) {ans += stack.pop();}return ans;}}