結果

問題 No.518 ローマ数字の和
ユーザー Tsukasa_Type
提出日時 2018-02-21 21:50:12
言語 Java
(openjdk 23)
結果
AC  
実行時間 139 ms / 2,000 ms
コード長 1,469 bytes
コンパイル時間 1,970 ms
コンパイル使用メモリ 77,840 KB
実行使用メモリ 51,724 KB
最終ジャッジ日時 2024-09-19 18:40:28
合計ジャッジ時間 5,148 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 19
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
	static Scanner sc = new Scanner(System.in);
	public static void main(String[] args) {
		int n = sc.nextInt();
		String[] a = {"IV","IX","XL","XC","CD","CM"};
		String[] b = {"IIII","VIIII","XXXX","LXXXX","CCCC","DCCCC"};
		StringBuilder sb = new StringBuilder();
		for (int i=0; i<n; i++) {
			String temp = sc.next();
			for (int j=0; j<6; j++) {
				temp = temp.replaceAll(a[j],b[j]);
			}
			sb.append(temp);
		}

		int total = 0;
		char[] ar = {'I','V','X','L','C','D','M'};
		int[] number = {1,5,10,50,100,500,1000};
		for (int i=0; i<sb.length(); i++) {
			for (int j=0; j<7; j++) {
				if (sb.charAt(i)==ar[j]) {total += number[j];}
			}
		}
		if (total > 3999) {System.out.println("ERROR");}
		else {
			int[] num = new int[7];
			for (int i=6; i>=0; i--) {
				num[i] = total/number[i];
				total = total%number[i];
			}
			StringBuilder ans = new StringBuilder();
			for (int i=6; i>=0; i--) {
				if (i==5 && num[5]==1 && num[4]==4) {ans.append("CM"); num[4]=0;}
				else if (i==4 && num[4]==4) {ans.append("CD");}
				else if (i==3 && num[3]==1 && num[2]==4) {ans.append("XC"); num[3]=0; num[2]=0;}
				else if (i==2 && num[2]==4) {ans.append("XL"); num[2]=0;}
				else if (i==1 && num[1]==1 && num[0]==4) {ans.append("IX"); i--; num[1]=0; num[0]=0;}
				else if (i==0 && num[0]==4) {ans.append("IV"); num[0]=0;}
				else {for (int j=0; j<num[i]; j++) {ans.append(ar[i]);}}
			}
			System.out.println(ans);
		}
	}
}
0