您的位置:首页 > 其它

leetcode之旅(11)-Integer to Roman

2016-03-29 23:05 246 查看

题目描述:

Given an integer, convert it to a roman numeral.

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

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems


准备知识看上篇博客

leetcode之旅(10)-Roman to Integer

思路:

当前这个数是否大于最大的权?若大于则循环判断有几个这样的权?若小于,则降低权进行判断,重复判断操作


代码:

public class Solution {
public String intToRoman(int num) {
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 result = "";
for (int i = 0; i < 13; i++)
{
while (num >= values[i]) //循环判断当前权值个数
{
num -= values[i];

result = result +numerals[i]; //append函数是向string 的后面追加字符或字符串。
}
}
return result;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode intToRoman 算法