本文主要是介绍leetcode之旅(11)-Integer to Roman,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:
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 questionShow 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之旅(11)-Integer to Roman的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!