結果

問題 No.518 ローマ数字の和
ユーザー momen999
提出日時 2017-05-31 18:25:30
言語 Haskell
(9.10.1)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,677 bytes
コンパイル時間 2,942 ms
コンパイル使用メモリ 169,728 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-09-21 20:25:32
合計ジャッジ時間 2,371 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 19
権限があれば一括ダウンロードができます
コンパイルメッセージ
Loaded package environment from /home/judge/.ghc/x86_64-linux-9.8.2/environments/default
[1 of 2] Compiling Main             ( Main.hs, Main.o )
[2 of 2] Linking a.out

ソースコード

diff #

toNum ns = iter 0 "" (reverse ns)
    where
        iter x _ [] = x
        iter x s (n:ns)
            | n == 'V'          = iter (x + 5) "V" ns
            | n == 'L'          = iter (x + 50) "L" ns
            | n == 'D'          = iter (x + 500) "D" ns
            | n == 'M'          = iter (x + 1000) "M" ns
            | n == 'I'          = case s of { "V" -> iter (x - 1) "" ns; "X" -> iter (x - 1) "" ns; _ -> iter (x + 1) "" ns; }
            | n == 'X'          = case s of { "L" -> iter (x - 10) "" ns; "C" -> iter (x - 10) "" ns; _ -> iter (x + 10) "X" ns; }
            | n == 'C'          = case s of { "D" -> iter (x - 100) "" ns; "M" -> iter (x - 100) "" ns; _ -> iter (x + 100) "C" ns; }
            | otherwise         = 0

toRoma n
    | n < 4000  = p1000 (f 3) ++ p100 (f 2) ++ p10 (f 1) ++ p1 (f 0)
    | otherwise = "ERROR"
    where
        f m = (n `div` (10^m)) `mod` 10
        p1000 x | x == 0    = ""
                | otherwise = "M" ++ p1000 (x - 1)
        p100 x  | x == 0    = ""
                | x == 9    = "CM"
                | x == 4    = "CD"
                | x >= 5    = "D" ++ p100 (x - 5)
                | otherwise = "C" ++ p100 (x - 1)
        p10 x   | x == 0    = ""
                | x == 9    = "XC"
                | x == 4    = "XL"
                | x >= 5    = "L" ++ p10 (x - 5)
                | otherwise = "X" ++ p10 (x - 1)
        p1 x    | x == 0    = ""
                | x == 9    = "IX"
                | x == 4    = "IV"
                | x >= 5    = "V" ++ p1 (x - 5)
                | otherwise = "I" ++ p1 (x - 1)

main = do
    getLine
    ns <- map toNum . words <$> getLine
    putStrLn $ toRoma $ sum ns
0