LeetCode!! 13. Roman to Integer && 12. Integer toRoman

参考资料:左程云算法课

13. Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9. 
X can be placed before L (50) and C (100) to make 40 and 90. 
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.

 

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

罗马数转成十进制数

思路:
以“IX”为例,I表示1,X表示10,值为 -1+10=9;
以“XCII”为例,X表示10,C表示100,值为 -10+100+1+1=92.
以“MXCII”为例, 1000+ -10 +100+1+1=1092
也就是说,把每个字符翻译成对应的数,如果后面的数大于自己,说明自己在最终加和结果中是一个负数;否则 自己是作为正数参与加和的。

 public int romanToInt(String s) {
         char[] str = s.toCharArray();
         int n = str.length;
         int[] nums = new int[n];
         for(int i=0;i<n;i++){
             switch(str[i]){
                 case 'I':
                 nums[i]=1;break;
                 case 'V':
                 nums[i]=5;break;
                 case 'X':
                 nums[i]=10;break;
                 case 'L':
                 nums[i]=50;break;
                 case 'C':
                 nums[i]=100;break;
                 case 'D':
                 nums[i]=500;break;
                 case 'M':
                 nums[i]=1000;break;
             }
         }
         int ans=0;
         for(int i=0;i<n-1;i++){
             if(nums[i]<nums[i+1]){
                 ans-=nums[i];
             }else{
                 ans+=nums[i];
             }
         }// end for
         return ans+nums[n-1];
     }

十进制数转成罗马数

思路:分别罗列出十进制每一位上的数字所对应的罗马数。对于输入数,先找其千位上的数字对应的罗马数,加进StringBuilder中;然后找百位、十位、个位。

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

        StringBuilder ans=new StringBuilder();
        ans.append(c[3][num/1000%10]);
        ans.append(c[2][num/100%10]);
        ans.append(c[1][num/10%10]);
        ans.append(c[0][num%10]);

        return ans.toString();
    }

你可能感兴趣的:(数据结构与算法,leetcode,算法,java)