LeetCode.12- Integer to Roman number string (Integer to Roman)

This is the first book of pleasure and delight 351 update, the first 376 Pian original

01 questions and look ready

Introduced today is LeetCode algorithm problem in Medium level of 6 title (overall title number is 12 ). Roman numerals of seven different symbols: I, V, X, L , C, D and M.

符号    值
I       1
V       5
X       10
L       50
C       100
D       500
M       1000

For example, written in Roman numerals 2 II, I added together by the two. 12 written XII, for short X + II.
27 written XXVII, that is XX + V + II.

Roman numerals are usually left to right, from largest to smallest. However, instead of four numbers IIII. In contrast, 4 written IV.
Because Iin Vbefore we get to do subtraction 4. The same principle applies to 9,9 is written IX. There are six instances of the use of subtraction:

IIt can be placed V(5) and Xprior to (10), to give 4 and 9.
XCan be placed L(50) and Cprior to (100), to give 40 and 90.
CIt can be placed D(500) and Mbefore (1000), to give 400 and 900.

Given an integer, convert it to Roman numerals. To ensure that the input is in the range of 1 to 3999. E.g:

Input: 3
Output: "III"

Input: 4
Output: "IV"

Input: 9
output: "IX"

Input: 58
Output: "LVIII"
Description: L = 50, V = 5 , III = 3.

Input: 1994
Output: "MCMXCIV"
Description: M = 1000, CM = 900 , XC = 90, IV = 4.

02 The first solution

Topics requirements we will turn into an integer number of strings to represent Rome, and Rome to integer number of strings before encountering the opposite.

Title defines num range, [1,3999]for common digital, relationship between those listed Rome and integer numbers below:

           900  CM    90  XC    9  IX

           800  DCCC  80  LXXX  8  VIII 
           700  DCC   70  LXX   7  VII
           600  DC    60  LX    6  VI
           500  D     50  L     5  V

           400  CD    40  XL    4  IV

3000  MMM  300  CCC   30  XXX   3  III
2000  MM   200  CC    20  XX    2  II
1000  M    100  C     10  X     1  I

We can correspondence between their divided into four groups:

  • The first group, the most significant bit is less than 4, the number corresponding to the Roman they are superimposed, for example, 1000 is M, 3000 is MMM.

  • The second group, the most significant bit is equal to 4, corresponding to their number in Roman beginning 5 together with Roman numbers beginning with 1, and two adjacent first few Roman relationship.

  • The third group, the highest level between 5-8, corresponding to the number of Roma is the beginning of the Roman number 5 is based on the overlay to keep up with the beginning of a number of Rome, it is also adjacent to the relationship between the two.

  • The fourth group, the maximum equal to 9, the number is the number of intervals corresponding to the Roman Roman composition beginning with 1, for example 900, in 1000 on behalf of Mthe former plus representatives 100 C, i.e. CM, an intermediate spacing both.

The combination of the above correspondence relationship, we different integers, Roman number array initialization string from high to low, sequentially calculates the number of Rome.

public String intToRoman(int num) {
    String[] roman = {"M", "D", "C", "L", "X", "V", "I"};
    int[] value = {1000, 500, 100, 50, 10, 5, 1};
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<value.length; i+=2) {
        // 得到当前num的最高位
        int tem = num/value[i];
        if (tem < 4) {
            // 叠加
            for (int j=0; j<tem; j++) {
                sb.append(roman[i]);
            }
        } else if (tem == 4) {
            // 相邻
            sb.append(roman[i]+roman[i-1]);
        } else if (tem > 4 && tem < 9) {
            // 相邻
            sb.append(roman[i-1]);
            for (int j=6; j<=tem; j++) {
                sb.append(roman[i]);
            }
        } else if (tem == 9) {
            // 间隔两位
            sb.append(roman[i]+roman[i-2]);
        }
        // 去掉已经参与计算的高位
        num = num%value[i];
    }
    return sb.toString();
}


03 The second solution

On the basis of the first solution, we will correspond to the initial elements of the array increased by 6 to 9 and 4 begin. Is still calculated from the low to high, and the first modulo solution utilized, different rounding, this solution is subtraction cycle, until the current value is less than the value num remaining subtracted, will find a need to reduce the to the number.

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


04 A third solution

There is also a tricky solution. Because the topics num limit the scope of, the maximum will not exceed 4000, we can num split into four parts, one thousand only four possible, 0 (num is a three-digit number), 2, 3, corresponding to one hundred there are 10 possible, 0 to 9, and ten bits are 10 possible, they are listed only need to sequentially take num different bits corresponding to the string.

The time complexity of this solution is O(1).

public static String intToRoman3(int num) {
    String M[] = {"", "M", "MM", "MMM"};
    String C[] = {"", "C", "CC", "CCC", "CD", 
            "D", "DC", "DCC", "DCCC", "CM"};
    String X[] = {"", "X", "XX", "XXX", "XL", 
            "L", "LX", "LXX", "LXXX", "XC"};
    String I[] = {"", "I", "II", "III", "IV", 
            "V", "VI", "VII", "VIII", "IX"};
    return M[num/1000] + C[(num%1000)/100] + 
            X[(num%100)/10] + I[num%10];
}


05 Summary

Thematic algorithm has been continuous days more than six months , the algorithm of feature articles 219 + articles, public Number dialog box reply [ data structures and algorithms ], [ algorithm ], [ data structures ] either a keyword to obtain a series of articles Collection .

That's all, if you have any good solution ideas, suggestions or other issues, you can exchange comments below, thumbs up, message forwarding and support is the greatest reward for me!

Guess you like

Origin www.cnblogs.com/xiaochuan94/p/11007474.html