[leetcode] Integer to Roman


Integer to Roman

Given an integer, convert it to a roman numeral.

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

tag: string, math

9/28/2015 update

class Solution {
public:
    vector<string> roman = {"M", "CM", "D", "CD","C","XC","L","XL" ,"X","IX","V","IV","I"};
    vector<int> value = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    string intToRoman(int num) {
        string ans;
        for(int i = 0; i < 13; i++){
            while(num >= value[i]){
                ans.append(roman[i]);
                num -= value[i];
            }
        }
        return ans;
    }
};

 

给定一个整数,转换为罗马数字。

我用了一堆if判断,特殊的数字有1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1

class Solution {
public:
    string intToRoman(int num) {
       string s;
       while(num >= 1000){
           num -= 1000;
           s.push_back('M');
       }
       if(num >= 900){
           num -= 900;
           s.append("CM");
       }
       else if(num >= 500){
           num -= 500;
           s.push_back('D');
       }
       else if(num >= 400){
           num -= 400;
           s.append("CD");
       }
       while(num >= 100){
           num -= 100;
           s.push_back('C');
       }
       if(num >= 90){
           num -= 90;
           s.append("XC");
       }
       else if(num >= 50){
           num -= 50;
           s.push_back('L');
       }
       else if(num >= 40){
           num -= 40;
           s.append("XL");
       }
       while(num >= 10){
           num -= 10;
           s.push_back('X');
       }
       if(num == 9){
           num -= 9;
           s.append("IX");
       }
       else if(num >= 5){
           num -= 5;
           s.push_back('V');
       }
       else if (num == 4){
           num -= 4;
           s.append("IV");
       }
       while(num > 0){
           num--;
           s.push_back('I');
       }
       return s;
    }
};

很暴力的做法。有人用了数组来使代码更简洁。

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

Selection_015

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.