本文主要是介绍[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.
【分析】
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
* 博客:
**********************************/
#include <iostream>
using 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];}//ifreturn result;}
private:string toRoman(int num,string str){string result;for(int i = 0;i < num;++i){result += str;}//forreturn result;}
};int main(){Solution solution;int num = 3999;string result = solution.intToRoman(num);// 输出cout<<result<<endl;return 0;
}
这篇关于[LeetCode]12.Integer to Roman的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!