【JAVA、C++】LeetCode 012 Integer to Roman

Given an integer, convert it to a roman numeral.

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

本题思路比较简单,难度主要集中在罗马数字本身,直接贴代码。

思路一,从高位开始:

JAVA:

	static 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" };
//不推荐用String类型,因为+的本质是建立StringBuilder()的过程
StringBuilder result = new StringBuilder();
for (int i = 0; i < values.length; i++) {
while (number >= values[i]) {
number -= values[i];
result.append(numerals[i]);
}
}
return new String(result);
}

C++:

 class Solution {
public:
string intToRoman(int num) {
vector<int> values = { , , , , , , , , , , , , };
string numerals[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X","IX", "V", "IV","I" };
string res;
for (int i = ; i < values.size(); i++)
while (num >= values[i]) {
num -= values[i];
res+=numerals[i];
}
return res;
}
};

思路二,从低位开始:

JAVA:

static public String intToRoman(int num) {
String Roman[][] = {
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "M", "MM", "MMM"}
};
StringBuilder result = new StringBuilder();
for(int i=0;i<Roman.length;i++,num/=10)
result.insert(0,Roman[i][num % 10]);
return new String(result);
}
上一篇:今天启动项目的时候报了一个错MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk.


下一篇:RookeyFrame Bug 表单管理 -> 查看表单 ->编辑字段页面 JS报错