`

LeetCode 12 - Integer to Roman

 
阅读更多

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

 

public String intToRoman(int num) {
    StringBuilder sb = new StringBuilder();
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(1, "I");
    map.put(5, "V");
    map.put(10, "X");
    map.put(50, "L");
    map.put(100, "C");
    map.put(500, "D");
    map.put(1000, "M");
    
    int base = 1000;
    while(base >= 1) {
        int n = num/base;
        if(n==4) {
            sb.append(map.get(base)).append(map.get(base*5));
        } else if(n==9) {
            sb.append(map.get(base)).append(map.get(base*10));
        } else {
            if(n>=5) {
                sb.append(map.get(base*5));
                n -= 5;
            }
            for(int i=0; i<n; i++) {
                sb.append(map.get(base));
            }
        }
        num %= base;
        base /= 10;
    }
    return sb.toString();
}

 

C++代码更简洁一些:

string intToRoman(int num) {
   unordered_map<int, char> map = {{1,'I'},{5,'V'},{10,'X'},{50,'L'},{100,'C'},{500,'D'},{1000, 'M'}};
   string res;
   vector<int> list = {1000, 100, 10, 1};
   for(auto n:list) {
       int d = num/n;
       num %= n;
       if(d == 0) continue;
       if(d < 4) {
           res.append(d, map[n]);
       } else if(d == 4) {
           res += map[n];
           res += map[n*5];
       } else if(d < 9) {
           res += map[n*5];
           if(d > 5)
               res.append(d-5, map[n]);
       } else if(d == 9) {
           res += map[n];
           res += map[n*10];
       }
   }
   return res;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics