java - 將整數轉換為羅馬數字 - Java




11 Answers

使用Java TreeMap和遞歸的緊湊實現:

import java.util.TreeMap;

public class RomanNumber {

    private final static TreeMap<Integer, String> map = new TreeMap<Integer, String>();

    static {

        map.put(1000, "M");
        map.put(900, "CM");
        map.put(500, "D");
        map.put(400, "CD");
        map.put(100, "C");
        map.put(90, "XC");
        map.put(50, "L");
        map.put(40, "XL");
        map.put(10, "X");
        map.put(9, "IX");
        map.put(5, "V");
        map.put(4, "IV");
        map.put(1, "I");

    }

    public final static String toRoman(int number) {
        int l =  map.floorKey(number);
        if ( number == l ) {
            return map.get(number);
        }
        return map.get(l) + toRoman(number-l);
    }

}

測試:

public void testRomanConversion() {

    for (int i = 1; i<= 100; i++) {
        System.out.println(i+"\t =\t "+RomanNumber.toRoman(i));
    }

}

這是我遇到麻煩的家庭作業。

我需要使用方法為Roman Numeral轉換器創建一個整數。 之後,我必須使用該程序用羅馬數字寫出1到3999,所以硬編碼就出來了。 我的代碼非常簡單; 它是一個基本的I / O循環,在使用我們在課堂上getIntegerFromUser包時可以退出。

有沒有辦法為字符串賦值,然後在調用方法時將它們一起添加?

更新:我從我的教授那裡得到了一些偽代碼來幫助我,雖然我明白他想說的是什麼,但我對if有一些麻煩。 我是否需要很多很多if語句,以便我的轉換器能夠正確處理羅馬數字格式,或者我是否可以更高效地執行此操作? 我已更新我的代碼以反映我的佔位符方法。

更新(2012年10月28日):我得到了它的工作。 這是我最終使用的內容:

public static String IntegerToRomanNumeral(int input) {
    if (input < 1 || input > 3999)
        return "Invalid Roman Number Value";
    String s = "";
    while (input >= 1000) {
        s += "M";
        input -= 1000;        }
    while (input >= 900) {
        s += "CM";
        input -= 900;
    }
    while (input >= 500) {
        s += "D";
        input -= 500;
    }
    while (input >= 400) {
        s += "CD";
        input -= 400;
    }
    while (input >= 100) {
        s += "C";
        input -= 100;
    }
    while (input >= 90) {
        s += "XC";
        input -= 90;
    }
    while (input >= 50) {
        s += "L";
        input -= 50;
    }
    while (input >= 40) {
        s += "XL";
        input -= 40;
    }
    while (input >= 10) {
        s += "X";
        input -= 10;
    }
    while (input >= 9) {
        s += "IX";
        input -= 9;
    }
    while (input >= 5) {
        s += "V";
        input -= 5;
    }
    while (input >= 4) {
        s += "IV";
        input -= 4;
    }
    while (input >= 1) {
        s += "I";
        input -= 1;
    }    
    return s;
}



Java Notes 6.0網站:

      /**
       * An object of type RomanNumeral is an integer between 1 and 3999.  It can
       * be constructed either from an integer or from a string that represents
       * a Roman numeral in this range.  The function toString() will return a
       * standardized Roman numeral representation of the number.  The function
       * toInt() will return the number as a value of type int.
       */
      public class RomanNumeral {

         private final int num;   // The number represented by this Roman numeral.

         /* The following arrays are used by the toString() function to construct
            the standard Roman numeral representation of the number.  For each i,
            the number numbers[i] is represented by the corresponding string, letters[i].
         */

         private static int[]    numbers = { 1000,  900,  500,  400,  100,   90,  
                                               50,   40,   10,    9,    5,    4,    1 };

         private static String[] letters = { "M",  "CM",  "D",  "CD", "C",  "XC",
                                             "L",  "XL",  "X",  "IX", "V",  "IV", "I" };

         /**
          * Constructor.  Creates the Roman number with the int value specified
          * by the parameter.  Throws a NumberFormatException if arabic is
          * not in the range 1 to 3999 inclusive.
          */
         public RomanNumeral(int arabic) {
            if (arabic < 1)
               throw new NumberFormatException("Value of RomanNumeral must be positive.");
            if (arabic > 3999)
               throw new NumberFormatException("Value of RomanNumeral must be 3999 or less.");
            num = arabic;
         }


         /*
          * Constructor.  Creates the Roman number with the given representation.
          * For example, RomanNumeral("xvii") is 17.  If the parameter is not a
          * legal Roman numeral, a NumberFormatException is thrown.  Both upper and
          * lower case letters are allowed.
          */
         public RomanNumeral(String roman) {

            if (roman.length() == 0)
               throw new NumberFormatException("An empty string does not define a Roman numeral.");

            roman = roman.toUpperCase();  // Convert to upper case letters.

            int i = 0;       // A position in the string, roman;
            int arabic = 0;  // Arabic numeral equivalent of the part of the string that has
                             //    been converted so far.

            while (i < roman.length()) {

               char letter = roman.charAt(i);        // Letter at current position in string.
               int number = letterToNumber(letter);  // Numerical equivalent of letter.

               i++;  // Move on to next position in the string

               if (i == roman.length()) {
                     // There is no letter in the string following the one we have just processed.
                     // So just add the number corresponding to the single letter to arabic.
                  arabic += number;
               }
               else {
                     // Look at the next letter in the string.  If it has a larger Roman numeral
                     // equivalent than number, then the two letters are counted together as
                     // a Roman numeral with value (nextNumber - number).
                  int nextNumber = letterToNumber(roman.charAt(i));
                  if (nextNumber > number) {
                       // Combine the two letters to get one value, and move on to next position in string.
                     arabic += (nextNumber - number);
                     i++;
                  }
                  else {
                       // Don't combine the letters.  Just add the value of the one letter onto the number.
                     arabic += number;
                  }
               }

            }  // end while

            if (arabic > 3999)
               throw new NumberFormatException("Roman numeral must have value 3999 or less.");

            num = arabic;

         } // end constructor


         /**
          * Find the integer value of letter considered as a Roman numeral.  Throws
          * NumberFormatException if letter is not a legal Roman numeral.  The letter 
          * must be upper case.
          */
         private int letterToNumber(char letter) {
            switch (letter) {
               case 'I':  return 1;
               case 'V':  return 5;
               case 'X':  return 10;
               case 'L':  return 50;
               case 'C':  return 100;
               case 'D':  return 500;
               case 'M':  return 1000;
               default:   throw new NumberFormatException(
                            "Illegal character \"" + letter + "\" in Roman numeral");
            }
         }


         /**
          * Return the standard representation of this Roman numeral.
          */
         public String toString() {
            String roman = "";  // The roman numeral.
            int N = num;        // N represents the part of num that still has
                                //   to be converted to Roman numeral representation.
            for (int i = 0; i < numbers.length; i++) {
               while (N >= numbers[i]) {
                  roman += letters[i];
                  N -= numbers[i];
               }
            }
            return roman;
         }


         /**
          * Return the value of this Roman numeral as an int.
          */
         public int toInt() {
            return num;
         }


      }



我寫了一個非常簡單的解決方案。 我們所要做的就是劃分並查找特定字母(或字母組合發生)的次數,並將其附加到StringBuilder對象sb 。 我們還應該跟踪剩餘的數量( num )。

public static String intToRoman(int num) {
    StringBuilder sb = new StringBuilder();
    int times = 0;
    String[] romans = new String[] { "I", "IV", "V", "IX", "X", "XL", "L",
            "XC", "C", "CD", "D", "CM", "M" };
    int[] ints = new int[] { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500,
            900, 1000 };
    for (int i = ints.length - 1; i >= 0; i--) {
        times = num / ints[i];
        num %= ints[i];
        while (times > 0) {
            sb.append(romans[i]);
            times--;
        }
    }
    return sb.toString();
} 



我喜歡AndréKramerOrten的回答,非常優雅,我特別喜歡它如何避免循環,我想到了另一種方法來處理它也避免循環。

它在輸入上使用整數除法和模數來從每個單元類型的硬編碼字符串數組中選擇正確的索引。

這裡的好處是你可以指定精確的轉換,具體取決於你是否需要加法或減法數字形式,即IIII對IV。 在這裡,我使用5x-1(4,9,14,19,40,90等)形式的所有數字的“減法形式”

通過簡單地使用其他加法或減法形式(即“IV”,“V”或“MMMM”,“MMMMM”)擴展千位數組來擴展它以允許更大的數字也是微不足道的。

對於獎勵積分,我實際上確保數字參數在問題的給定範圍內。

public class RomanNumeralGenerator {
    static final int MIN_VALUE = 1;
    static final int MAX_VALUE = 3999;
    static final String[] RN_M = {"", "M", "MM", "MMM"};
    static final String[] RN_C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    static final String[] RN_X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    static final String[] RN_I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

    public String generate(int number) {
        if (number < MIN_VALUE || number > MAX_VALUE) {
            throw new IllegalArgumentException(
                    String.format(
                            "The number must be in the range [%d, %d]",
                            MIN_VALUE,
                            MAX_VALUE
                    )
            );
        }

        return new StringBuilder()
                .append(RN_M[number / 1000])
                .append(RN_C[number % 1000 / 100])
                .append(RN_X[number % 100 / 10])
                .append(RN_I[number % 10])
                .toString();
    }
}



我的解決方案是在函數getRoman中:

public  String getRoman(int number) {

    String riman[] = {"M","XM","CM","D","XD","CD","C","XC","L","XL","X","IX","V","IV","I"};
    int arab[] = {1000, 990, 900, 500, 490, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    StringBuilder result = new StringBuilder();
    int i = 0;
    while (number > 0 || arab.length == (i - 1)) {
        while ((number - arab[i]) >= 0) {
            number -= arab[i];
            result.append(riman[i]);
        }
        i++;
    }
    return result.toString();
}



我想如果你仔細研究羅馬數字的理論你不需要數字4,9,40等的映射,因為理論告訴我們羅馬數字是否是IV = 5-1 = 4,因此當前綴小於在這種情況下,你必須從後續數字中減去前一個數字以獲得實際值,這就是我在問題代碼中加入的內容,如有必要,請查看並指出任何錯誤,我遵循了這個表格來設計我的邏輯 - http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm

import java.util.Set;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;

public class RomanStringToIntegerConversion {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)));
        String[] romanString = br.readLine().split("");

        HashMap<String, Integer> romanToIntegerMap = new HashMap<String, Integer>();
        romanToIntegerMap.put("I", 1);
        romanToIntegerMap.put("V", 5);
        romanToIntegerMap.put("X", 10);
        romanToIntegerMap.put("L", 50);
        romanToIntegerMap.put("C", 100);
        romanToIntegerMap.put("D", 500);
        romanToIntegerMap.put("M", 1000);

        int numLength = romanString.length;
        Set<Integer> lessIndices = new HashSet<Integer>();

        for(int i = 0; i < numLength; ++i){
            if(i+1 < numLength){
                if(romanToIntegerMap.get(romanString[i]) < romanToIntegerMap.get(romanString[i+1]))
                    lessIndices.add(i);
            }
        }

        int num = 0;
        for(int i = 0; i < numLength;){
            if(!lessIndices.contains(i)){
                num = num + romanToIntegerMap.get(romanString[i]);
                ++i;
            }
            else{
                num = num + romanToIntegerMap.get(romanString[i+1]) - romanToIntegerMap.get(romanString[i]);
                i+=2;
            }
        }
        System.out.println("The integer representation of the roman numeral is : " + num);
    }
}



enum Numeral {
        I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
        int weight;

        Numeral(int weight) {
            this.weight = weight;
        }
    };

    public static String roman(long n) {

        if( n <= 0) {
            throw new IllegalArgumentException();
        }

        StringBuilder buf = new StringBuilder();

        final Numeral[] values = Numeral.values();
        for (int i = values.length - 1; i >= 0; i--) {
            while (n >= values[i].weight) {
                buf.append(values[i]);
                n -= values[i].weight;
            }
        }
        return buf.toString();
    }

    public static void test(long n) {
        System.out.println(n + " = " + roman(n));
    }

    public static void main(String[] args) {
        test(1999);
        test(25);
        test(944);
        test(0);
    }



這可能有所幫助:

using System;

using System.Text;

public class Test
{

public static string ToRoman(int number)
{
    StringBuilder br=new StringBuilder("");
    while(number!=0)
    {
        if(number>=1000)
        {
            br.Append("M");
            number-=1000;   
        }
        if(number>=900)
        {
            br.Append("CM");
            number-=900;    
        }
        if(number>=500)
        {
            br.Append("D");
            number-=500;    
        }
        if(number>=400)
        {
            br.Append("CD");
            number-=400;    
        }
        if(number>=100)
        {
            br.Append("C");
            number-=100;    
        }
        if(number>=90)
        {
            br.Append("XC");
            number-=90; 
        }
        if(number>=50)
        {
            br.Append("L");
            number-=50; 
        }
        if(number>=40)
        {
            br.Append("XL");
            number-=40; 
        }
        if(number>=10)
        {
            br.Append("X");
            number-=10; 
        }
        if(number>=9)
        {
            br.Append("IX");
            number-=9;  
        }
        if(number>=5)
        {
            br.Append("V");
            number-=5;  
        }
        if(number>=4)
        {
            br.Append("IV");
            number-=4;  
        }
        if(number>=1)
        {
            br.Append("I");
            number-=1;  
        }
    }
    return br.ToString();
}
public static void Main()
{
    Console.WriteLine(ToRoman(int.Parse(Console.ReadLine())));
}
}



通過利用enum基於OP自己的解決方案的替代解決方案。 此外,還包括解析器和往返測試。

public class RomanNumber {
    public enum Digit {
        M(1000, 3),
        CM(900, 1),
        D(500, 1),
        CD(400, 1),
        C(100, 3),
        XC(90, 1),
        L(50, 1),
        XL(40, 1),
        X(10, 3),
        IX(9, 1),
        V(5, 1),
        IV(4, 1),
        I(1, 3);

        public final int value;
        public final String symbol = name();
        public final int maxArity;

        private Digit(int value, int maxArity) {
            this.value = value;
            this.maxArity = maxArity;
        }
    }

    private static final Digit[] DIGITS = Digit.values();

    public static String of(int number) {
        if (number < 1 || 3999 < number) {
            throw new IllegalArgumentException(String.format(
                    "Roman numbers are only defined for numbers between 1 and 3999 (%d was given)",
                    number
            ));
        }

        StringBuilder sb = new StringBuilder();
        for (Digit digit : DIGITS) {
            int value = digit.value;
            String symbol = digit.symbol;

            while (number >= value) {
                sb.append(symbol);
                number -= value;
            }
        }

        return sb.toString();
    }

    public static int parse(String roman) {
        if (roman.isEmpty()) {
            throw new NumberFormatException("The empty string does not comprise a valid Roman number");
        }

        int number = 0;
        int offset = 0;
        for (Digit digit : DIGITS) {
            int value = digit.value;
            int maxArity = digit.maxArity;
            String symbol = digit.symbol;

            for (int i = 0; i < maxArity && roman.startsWith(symbol, offset); i++) {
                number += value;
                offset += symbol.length();
            }
        }
        if (offset != roman.length()) {
            throw new NumberFormatException(String.format(
                    "The string '%s' does not comprise a valid Roman number",
                    roman
            ));
        }
        return number;
    }

    /** TESTS */
    public static void main(String[] args) {

        /* Demonstrating round-trip for all possible inputs. */

        for (int number = 1; number <= 3999; number++) {
            String roman = of(number);
            int parsed = parse(roman);
            if (parsed != number) {
                System.err.format(
                        "ERROR: number: %d, roman: %s, parsed: %d\n",
                        number,
                        roman,
                        parsed
                );
            }
        }

        /* Some illegal inputs. */

        int[] illegalNumbers = { -1, 0, 4000, 4001 };
        for (int illegalNumber : illegalNumbers) {
            try {
                of(illegalNumber);
                System.err.format(
                        "ERROR: Expected failure on number %d\n",
                        illegalNumber
                );
            } catch (IllegalArgumentException e) {
                // Failed as expected.
            }
        }

        String[] illegalRomans = { "MMMM", "CDCD", "IM", "T", "", "VV", "DM" };
        for (String illegalRoman : illegalRomans) {
            try {
                parse(illegalRoman);
                System.err.format(
                        "ERROR: Expected failure on roman %s\n",
                        illegalRoman
                );
            } catch (NumberFormatException e) {
                // Failed as expected.
            }
        }
    }
}



Simplest solution:

public class RomanNumerals {

    private static int [] arabic = {50, 40, 10, 9, 5, 4, 1};

    private static String [] roman = {"L", "XL", "X", "IX", "V", "IV", "I"};

    public static String convert(int arabicNumber) {

        StringBuilder romanNumerals = new StringBuilder();
        int remainder = arabicNumber;

        for (int i=0;i<arabic.length;i++) {

            while (remainder >= arabic[i]) {
                romanNumerals.append(roman[i]);
                remainder -= arabic[i];
            }
        }

        return romanNumerals.toString();
    }
}



I did this before three years, may be it helps you:

public class ToRoman
{

    public static String toRoman(int number)
    {
        StringBuilder br = new StringBuilder("");
        while(number!=0)
        {
            while(number>=1000)
            {
                br.append("M");
                number-=1000;   
            }
            while(number>=900)
            {
                br.append("CM");
                number-=900;    
            }
            while(number>=500)
            {
                br.append("D");
                number-=500;    
            }
            while(number>=400)
            {
                br.append("CD");
                number-=400;    
            }
            while(number>=100)
            {
                br.append("C");
                number-=100;    
            }
            while(number>=90)
            {
                br.append("XC");
                number-=90; 
            }
            while(number>=50)
            {
                br.append("L");
                number-=50; 
            }
            while(number>=40)
            {
                br.append("XL");
                number-=40; 
            }
            while(number>=10)
            {
                br.append("X");
                number-=10; 
            }
            while(number>=9)
            {
                br.append("IX");
                number-=9;  
            }
            while(number>=5)
            {
                br.append("V");
                number-=5;  
            }
            while(number>=4)
            {
                br.append("IV");
                number-=4;  
            }
            while(number>=1)
            {
                br.append("I");
                number-=1;  
            }
        }
        return br.toString();
    }

    public static void main(String [] args)
    {
        System.out.println(toRoman(2000));
    }
}



Related

java methods roman-numerals