leetcode title brush 12 (Integer Roman numerals)

Subject description:

Roman numeral characters comprising the following seven: I, V, X, L, C, D and M.

Numerical character
the I. 1
V. 5
X-10
L 50
C 100
D 500
M 1000
, for example, 2 written as Roman numerals II, namely 1.12 written as two parallel XII, namely X + II. 27 written as XXVII, namely XX + V + II.

Typically, small numbers of Roman numerals to the right in large numbers. But there are exceptions, for example, do not write 4 IIII, but IV. In the left number 5 number 1, the number of large numbers equal to the value represented by a reduced number 5 obtained 4. Likewise, the number 9 is represented as IX. This special rule applies only to the following six cases:

I may be on the left V (5) and X (10), and to represent 4 and 9.
X L can be placed on the left (50) and C (100), and 40 and 90 are represented. 
C may be placed on D (500) and M (1000) to the left, to 400 and 900 represent.
Given an integer, convert it to a Roman numeral. To ensure that the input is in the range of 1 to 3999.

Example 1:

Input: 3
Output: "III"
Example 2:

Input: 4
Output: "IV"
Example 3:

Input: 9
Output: "IX"
Example 4:

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

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

String class and StringBuilder class differences:

string itself is immutable, it can only be assigned once, each time content is changed, will generate a new object, then the original object reference to the new object, and each time new objects will have an impact on system performance, It will reduce the efficiency of .NET compiler.

The StringBuilder class is different, each operation is to operate the object itself, instead of generating a new object, its footprint will increase and expand the content, so do a lot of modifications in the operation, will not generate a lot of anonymous objects affect system performance.

By the answer:

class Solution {     //贪心算法
    public String intToRoman(int num) {
        int[] nums={1000,900,500,400,100,90,50,40,10,9,5,4,1};     //将特殊数字与其罗马字符对应
        String[] rom={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        StringBuilder str=new StringBuilder();   
        int index=0;
        while(index<13){
            while(num>=nums[index]){
                str.append(rom[index]);
                num-=nums[index];      //从大到小开始减
            }
            index++;
        }
        return str.toString();     //返回一个以字符串表示的str对象
    }
}

 

Published 88 original articles · won praise 10 · views 2549

Guess you like

Origin blog.csdn.net/ZhangShaoYan111/article/details/104580249