LeetCode OJ-- Integer to Roman @

@表示有更优解法

https://oj.leetcode.com/problems/integer-to-roman/

将自然数,转换成罗马数字,输入范围为 1 ~ 3999,因为罗马数没有0.

用一个map,表示 1 ~ 9, 10 ~ 90, 100 ~ 900, 1000 ~ 3000,然后,把相应的罗马字母存起来。

之后,求出输入有几个 1000 ,几个 100 ,几个1来。

#include <iostream>
#include <map>
#include <string>
using namespace std;

class Solution {

public:
    string intToRoman(int num) {
        map<int,string> I2R;
        I2R.insert(make_pair( 1,"I"));
        I2R.insert(make_pair( 2,"II"));
        I2R.insert(make_pair( 3,"III"));
        I2R.insert(make_pair( 4,"IV"));
        I2R.insert(make_pair( 5,"V"));
        I2R.insert(make_pair( 6,"VI"));
        I2R.insert(make_pair( 7,"VII"));
        I2R.insert(make_pair( 8,"VIII"));
        I2R.insert(make_pair( 9,"IX"));
        I2R.insert(make_pair( 10,"X"));
        I2R.insert(make_pair( 20,"XX"));
        I2R.insert(make_pair( 30,"XXX"));
        I2R.insert(make_pair( 40,"XL"));
        I2R.insert(make_pair( 50,"L"));
        I2R.insert(make_pair( 60,"LX"));
        I2R.insert(make_pair( 70,"LXX"));
        I2R.insert(make_pair( 80,"LXXX"));
        I2R.insert(make_pair( 90,"XC"));
        I2R.insert(make_pair( 100,"C"));
        I2R.insert(make_pair( 200,"CC"));
        I2R.insert(make_pair( 300,"CCC"));
        I2R.insert(make_pair( 400,"CD"));
        I2R.insert(make_pair( 500,"D"));
        I2R.insert(make_pair( 600,"DC"));
        I2R.insert(make_pair( 700,"DCC"));
        I2R.insert(make_pair( 800,"DCCC"));
        I2R.insert(make_pair( 900,"CM"));
        I2R.insert(make_pair( 1000,"M"));
        I2R.insert(make_pair( 2000,"MM"));
        I2R.insert(make_pair( 3000,"MMM"));
        
        string ans;
    
        int this_time = 0;
        for(int jinzhi = 1000; jinzhi > 0; jinzhi = jinzhi / 10)
        {
            this_time = num / jinzhi;
            this_time = this_time * jinzhi;
            if(this_time > 0)
                ans = ans + I2R[this_time];
            num = num % jinzhi;
        }

        return ans;
    }
};

更优解法,来自九章。

/**
 * Copyright: NineChapter
 * - Algorithm Course, Mock Interview, Interview Questions
 * - More details on: http://www.ninechapter.com/
 */

public class Solution {
    public String intToRoman(int num) {
        if(num <= 0) {
            return "";
        }
        int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        StringBuilder res = new StringBuilder();
        int digit=0;
        while (num > 0) {
            int times = num / nums[digit];
            num -= nums[digit] * times;
            for ( ; times > 0; times--) {
                res.append(symbols[digit]);
            }
            digit++;
        }
        return res.toString();
    }
}
原文地址:https://www.cnblogs.com/qingcheng/p/3863914.html