[Java] Algoritma Bilangan Romawi

Berawal dari ngobrol iseng-iseng dengan temen gw ( Kamplenk SKom ) sepulang dari ngopi bareng, beliau kebetulan nanya soal algoritma bilangan romawi untuk digunakan sebagai nomer surat. Kebetulan karena waktu gw agak kosong, iseng-iseng bikin kayak ginian ( setelah dibantu om google juga sih :p ).

package com.edw.main;

public class RomanNumber {
    
    private static final char[] ROMAWI = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
    private static final int MAX = 1000; 
    private static final int[][] DIGITS = {
        {}, {0}, {0, 0}, {0, 0, 0}, {0, 1}, {1},
        {1, 0}, {1, 0, 0}, {1, 0, 0, 0}, {0, 2}}; 
        // konstanta digit modulus 10, 
        // array ke 4(0,1) maksudnya IV, array ke 9(0,2) --> IX

    public static String int2roman(int number) {
        if (number <= 0) {
            return "N";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0, m = MAX; m > 0; m /= 10, i += 2) {
            int[] d = DIGITS[(number / m) % 10];
            for (int n : d) {
                sb.append(ROMAWI[i - n]);
            }
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
        System.out.println(int2roman(1990));
        System.out.println(int2roman(2012));
        System.out.println(int2roman(231));
    }
}

Oi plenk, udah jadi nih wkkwkwk….

Google+

No Comments

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)