C++实现LeetCode(12.整数转化成罗马数字)

[LeetCode] 12. Integer to Roman 整数转化成罗马数字

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I                   1
V                  5
X                 10
L                  50
C                100
D                 500
M                1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M(1000) to make 400 and 900.

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

Example 1:

Input: 3
Output: "III"

Example 2:

Input: 4
Output: "IV"

Example 3:

Input: 9
Output: "IX"

Example 4:

Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

Example 5:

Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

之前那篇文章写的是罗马数字转化成整数 Roman to Integer, 这次变成了整数转化成罗马数字,基本算法还是一样。由于题目中限定了输入数字的范围 (1 - 3999), 使得题目变得简单了不少。

I - 1

V - 5

X - 10

L - 50

C - 100 

D - 500

M - 1000

例如整数 1437 的罗马数字为 MCDXXXVII, 我们不难发现,千位,百位,十位和个位上的数分别用罗马数字表示了。 1000 - M, 400 - CD, 30 - XXX, 7 - VII。所以我们要做的就是用取商法分别提取各个位上的数字,然后分别表示出来:

100 - C

200 - CC

300 - CCC

400 - CD

500 - D

600 - DC

700 - DCC

800 - DCCC

900 - CM

可以分为四类,100 到 300 一类,400 一类,500 到 800 一类,900 最后一类。每一位上的情况都是类似的,代码如下:

解法一:

class Solution {
public:
    string intToRoman(int num) {
        string res = "";
        vector<char> roman{'M', 'D', 'C', 'L', 'X', 'V', 'I'};
        vector<int> value{1000, 500, 100, 50, 10, 5, 1};
        for (int n = 0; n < 7; n += 2) {
            int x = num / value[n];
            if (x < 4) {
                for (int i = 1; i <= x; ++i) res += roman[n];
            } else if (x == 4) {
                res = res + roman[n] + roman[n - 1];
            } else if (x > 4 && x < 9) {
                res += roman[n - 1];
                for (int i = 6; i <= x; ++i) res += roman[n];
            } else if (x == 9) {
                res = res + roman[n] + roman[n - 2];
            }
            num %= value[n];
        }
        return res;
    }
};

本题由于限制了输入数字范围这一特殊性,故而还有一种利用贪婪算法的解法,建立一个数表,每次通过查表找出当前最大的数,减去再继续查表,参见代码如下:

解法二:

class Solution {
public:
    string intToRoman(int num) {
        string res = "";
        vector<int> val{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        vector<string> str{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        for (int i = 0; i < val.size(); ++i) {
            while (num >= val[i]) {
                num -= val[i];
                res += str[i];
            }
        }
        return res;
    }
};

下面这种方法个人感觉属于比较投机取巧的方法,把所有的情况都列了出来,然后直接按位查表,O(1) 的时间复杂度啊,参见代码如下:

解法三:

class Solution {
public:
    string intToRoman(int num) {
        string res = "";
        vector<string> v1{"", "M", "MM", "MMM"};
        vector<string> v2{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        vector<string> v3{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        vector<string> v4{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        return v1[num / 1000] + v2[(num % 1000) / 100] + v3[(num % 100) / 10] + v4[num % 10];
    }
};

到此这篇关于C++实现LeetCode(12.整数转化成罗马数字)的文章就介绍到这了,更多相关C++实现整数转化成罗马数字内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(13.罗马数字转化成整数)

    [LeetCode] 13. Roman to Integer 罗马数字转化成整数 Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol       Value I                  1 V                 5 X                10 L                 50 C                100 D 

  • C++实现LeetCode(45.跳跃游戏之二)

    [LeetCode] 45. Jump Game II 跳跃游戏之二 Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last i

  • C++实现LeetCode(55.跳跃游戏)

    [LeetCode] 55. Jump Game 跳跃游戏 Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach th

  • C++实现LeetCode(768.可排序的最大块数之二)

    [LeetCode] 768.Max Chunks To Make Sorted II 可排序的最大块数之二 This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements cou

  • C++实现LeetCode(11.装最多水的容器)

    [LeetCode] 11. Container With Most Water 装最多水的容器 Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two

  • C++实现LeetCode(84.直方图中最大的矩形)

    [LeetCode] 84. Largest Rectangle in Histogram 直方图中最大的矩形 Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width of e

  • C++实现LeetCode(769.可排序的最大块数)

    [LeetCode] 769.Max Chunks To Make Sorted 可排序的最大块数 Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk.  After concatenating them,

  • C++实现LeetCode(42.收集雨水)

    [LeetCode] 42. Trapping Rain Water 收集雨水 Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,

  • C++实现LeetCode(12.整数转化成罗马数字)

    [LeetCode] 12. Integer to Roman 整数转化成罗马数字 Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol       Value I                   1 V                  5 X                 10 L                  50 C                100

  • java将一个整数转化成二进制代码示例

    将一个整数转化成二进制的方法: 1 方法1:使用BigInteger类: @Test public void test1(){ BigInteger b=new BigInteger("10");//1010 System.out.println(b.toString(2));//0 b=new BigInteger("1"); System.out.println(b.toString(2));//1 b=new BigInteger("255"

  • 将CString字符串输入转化成整数的实现方法

    如下所示: BOOL IsHexFormat(LPCTSTR pStr) { if (pStr[0] == L'0' && ((pStr[1] == L'x') || (pStr[1] == L'X'))){ return TRUE; } return FALSE; } BOOL IsInputValid(LPCTSTR pStr) { int i; BOOL res; BOOL IsHex; i = 0; res = TRUE; IsHex = IsHexFormat(pStr); wh

  • Android编程实现将时间转化成几分钟前、几天前等形式的工具类

    本文实例讲述了Android编程实现将时间转化成几分钟前.几天前等形式的工具类.分享给大家供大家参考,具体如下: 描述: 在Android开发客户端的时候,是在会显示时间是多久之前,比如10分钟前,8小时前,一月前等等.下面提供一个工具类. 代码: public class TimeUtil { private final static long minute = 60 * 1000;// 1分钟 private final static long hour = 60 * minute;// 1

  • 基于JavaScript将表单序列化类型的数据转化成对象的处理(允许对象中包含对象)

    表单序列化类型的数据是指url传递的数据的格式,形如"key=value&key=value&key=value"这样的key/value的键值对.一般来说使用jQuery的$.fn.serialize函数能达到这样的效果.如何将这样的格式转化为对象? 我们知道使用jQuery的$.fn.serializeArray函数得到的是一个如下结构的对象 [ { name: "startTime" value: "2015-12-02 00:00:

  • FireFox下XML对象转化成字符串的解决方法

    解决方法如下: 复制代码 代码如下: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>xml转化成字符串</title> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script language=&qu

  • C++中几种将整数转换成二进制输出的方法总结

    看<编程之美>第二节的时候,它是定义的一个整型,然后取位.但是他的那个或运算符号好像写错了,写成了异或符号"^",应该是"|".我就突然对二进制的输出感兴趣了.想知道怎样输出二进制.我们知道C++输出十六进制是cout〈〈hex〈〈 a:而八进制是cout〈〈 ocx〈〈 a;二进制则没有默认的输出格式,需要自己写函数进行转换,于是上网搜索了一下.网上思路真是广泛啊. 下面列出一些方法.  #include 〈iostream〉 #include 〈li

  • 相对路径转化成绝对路径

    提取 Gregarius中的一个函数.可以把网页中的相对路径自动转化成绝对路径. <?  function relative_to_absolute($content, $feed_url) {      preg_match('/(http|https|ftp):\/\//', $feed_url, $protocol);      $server_url = preg_replace("/(http|https|ftp|news):\/\//", "", 

  • java8、jdk8日期转化成字符串详解

    java8.jdk8日期转化成字符串 新建日期工具类:DateUtils 新建方法:parseDate 实现方法parseDate public static String parseDate(LocalDate localDate,String pattern) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); return localDate.format(dateTimeFormatt

随机推荐