leetcode-12 Integer to Roman
2016-11-01 23:01
239 查看
Question:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
阿拉伯数字与罗马数字的对应关系为:
String roms[] = {"I", "V", "X", "L", "C", "D", "M"};
int aras[] = {1, 5, 10, 50, 100, 500, 1000};
其中,特殊的是:
当i % 2 == 0时(偶数),aras[i] - aras[i-2] = roms[i-2] + roms[i];
当i % 2 != 0 时(奇数),aras[i] - aras[i-1] = roms[i-1] + roms[i];
java代码如下:
public class Solution {
public String intToRoman(int num) {
String roms[] = {"I", "V", "X", "L", "C", "D", "M"};
int aras[] = {1, 5, 10, 50, 100, 500, 1000};
int temp = num;
String res = "";
for(int i = 6; i >= 0; i --){
int p = temp / aras[i];
if(p >= 1){
for(int j = 0; j < p; j ++){
res += roms[i];
}
temp = temp % aras[i];
i ++;
}
else{
if(i > 0 && i % 2 == 0){
if(temp / (aras[i] - aras[i-2]) == 1){
res = res + roms[i-2] + roms[i];
temp = temp - (aras[i] - aras[i-2]);
}
}
else if(i % 2 != 0){
if(temp / (aras[i] - aras[i-1]) == 1){
res = res + roms[i-1] + roms[i];
temp = temp - (aras[i] - aras[i-1]);
}
}
}
}
return res;
}
}
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
阿拉伯数字与罗马数字的对应关系为:
String roms[] = {"I", "V", "X", "L", "C", "D", "M"};
int aras[] = {1, 5, 10, 50, 100, 500, 1000};
其中,特殊的是:
当i % 2 == 0时(偶数),aras[i] - aras[i-2] = roms[i-2] + roms[i];
当i % 2 != 0 时(奇数),aras[i] - aras[i-1] = roms[i-1] + roms[i];
java代码如下:
public class Solution {
public String intToRoman(int num) {
String roms[] = {"I", "V", "X", "L", "C", "D", "M"};
int aras[] = {1, 5, 10, 50, 100, 500, 1000};
int temp = num;
String res = "";
for(int i = 6; i >= 0; i --){
int p = temp / aras[i];
if(p >= 1){
for(int j = 0; j < p; j ++){
res += roms[i];
}
temp = temp % aras[i];
i ++;
}
else{
if(i > 0 && i % 2 == 0){
if(temp / (aras[i] - aras[i-2]) == 1){
res = res + roms[i-2] + roms[i];
temp = temp - (aras[i] - aras[i-2]);
}
}
else if(i % 2 != 0){
if(temp / (aras[i] - aras[i-1]) == 1){
res = res + roms[i-1] + roms[i];
temp = temp - (aras[i] - aras[i-1]);
}
}
}
}
return res;
}
}
相关文章推荐
- [leetcode 12] Integer to Roman
- Leetcode_12_Integer to Roman
- LeetCode 12 - Integer to Roman
- leetcode[12]Integer to Roman
- [Leetcode 44] 12 Integer To Roman
- leetcode12 Integer to Roman
- LeetCode12: Integer to Roman
- leetcode_12题——Integer to Roman(string,数学问题)
- LeetCode12~14 Integer to Roman/Roman to Integer/Longest Common Prefix
- [Leetcode] 12 - Integer to Roman
- Leetcode 12 Integer to Roman整数变罗马
- [LeetCode]12.Integer to Roman
- Java [leetcode 12] Integer to Roman
- [LeetCode]12 Integer to Roman
- Integer to Roman_Leetcode_#12
- [LeetCode 12] Integer to Roman
- leetcode.12----------Integer to Roman
- LeetCode 12 - Integer to Roman
- LeetCode 12 Integer to Roman(C,C++,Java,Python)
- [Leetcode] 12. Integer to Roman