Monday, July 7, 2014

Leetcode - Roman to Integer || Integer to Roman

把罗马数字转化成数字。
罗马数字的表示方法:
基本字符
I
V
X
L
C
D
M
对应数字
1
5
10
50
100
500
1000
  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
  2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
  3. 小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
  4. 正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)
  5. 在一个数的上面画一条横线,表示这个数扩大1000倍。

[Thoughts]:
public class Solution {
    public int romanToInt(String s) {
        if(s == null || s.length() ==0) return 0;
        s.toUpperCase();
        int num = 0;
        int pre = Integer.MAX_VALUE;
        for(int i = 0; i < s.length(); i++){
            int cur = map(s.charAt(i));
            num     += cur;
            if(pre < cur ){//在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
                num = num - pre*2 ;
            }
            pre = cur;
        }
        return num;
    }
    
    public int map(char c){
        switch(c){
            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:
                return 0;
        }
    }
}

II: Integer to Roman
[Thoughts]:
public class Solution {
    public String intToRoman(int num) {
      String str = "";
      String[] symbol = {"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};
      for(int i = 0; num != 0; i++){
          while(num >= value[i]){
              num -= value[i];
              str += symbol[i];
          }
      }
      
      return str; 
    }
}

还可以具体算
public class Solution {
    public String intToRoman(int num) {
       String re="";
     int chu = 1000;
     while(chu>=1){
      int n = num/chu;
      if(chu==1000){
       for(int i=0;i< n;i++){
        re+="M";
       }
      }else if(chu==100){
       if(n< 4){
        for(int i=0;i< n;i++){
         re+='C';
        }
       }else if(n==4){
        re+="CD";
       }else if(n< 9){
        re+='D';
        for(int i=0;i< n-5;i++){
         re+='C';
        }
       }else{
        re+="CM";
       }
      }else if(chu==10){
       if(n< 4){
        for(int i=0;i< n;i++){
         re+='X';
        }
       }else if(n==4){
        re+="XL";
       }else if(n< 9){
        re+='L';
        for(int i=0;i< n-5;i++){
         re+='X';
        }
       }else{
        re+="XC";
       }
      }else{
       if(n< 4){
        for(int i=0;i< n;i++){
         re+='I';
        }
       }else if(n==4){
        re+="IV";
       }else if(n< 9){
        re+='V';
        for(int i=0;i< n-5;i++){
         re+='I';
        }
       }else{
        re+="IX";
       }
      }
      num=num-n*chu;
      chu=chu/10;
     }
     return re; 
    }
}

No comments:

Post a Comment