本文共 1274 字,大约阅读时间需要 4 分钟。
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
I = 1;
V = 5; X = 10; L = 50; C = 100; D = 500; M = 1000;还有一些特殊的:每两个阶段的之间有一个减法的表示,比如900=CM, C写在M前面表示M-C。
求商得到每个罗马文字的个数(如:3999 / 1000 = 3 结果有3个M)
/********************************** 日期:2015-01-21* 作者:SJF0115* 题目: 12.Integer to Roman* 网址:https://oj.leetcode.com/problems/integer-to-roman/* 结果:AC* 来源:LeetCode* 博客:**********************************/#includeusing namespace std;class Solution {public: string intToRoman(int num) { string result; string roman[] = {"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}; int count; // 转换为罗马数字 for(int i = 0;i < 13;++i){ count = num / value[i]; result += toRoman(count,roman[i]); num = num % value[i]; }//if return result; }private: string toRoman(int num,string str){ string result; for(int i = 0;i < num;++i){ result += str; }//for return result; }};int main(){ Solution solution; int num = 3999; string result = solution.intToRoman(num); // 输出 cout< <