[LeetCode-Algorithms-12] "Integer to Roman" (2017.10.2-WEEK5)

来源:互联网 发布:淘宝彩票是真的吗 编辑:程序博客网 时间:2024/05/21 09:15

题目链接:Integer to Roman


  • 题目描述:

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.


(1)思路:和上次那个Roman to Integer 一样,需要先搞清楚罗马字母的表示方法。然后用贪心算法,每次选择数字中能表达的最大值。

(2)代码:

class Solution {  public:      string intToRoman(int num) {          string ans;            string symbol[] = {"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};        for (int i = 0; num != 0; i++) {            while (num >= value[i]) {                num -= value[i];                ans += symbol[i];            }        }        return ans;    }};

(3)提交结果:

这里写图片描述

原创粉丝点击