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                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 a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

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

Example 5:

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

罗马数转化成数字问题,我们需要对于罗马数字很熟悉才能完成转换。以下截自百度百科:

罗马数字是最早的数字表示方式,比阿拉伯数字早2000多年,起源于罗马。

如今我们最常见的罗马数字就是钟表的表盘符号:Ⅰ,Ⅱ,Ⅲ,Ⅳ(IIII),Ⅴ,Ⅵ,Ⅶ,Ⅷ,Ⅸ,Ⅹ,Ⅺ,Ⅻ……

对应阿拉伯数字(就是现在国际通用的数字),就是1,2,3,4,5,6,7,8,9,10,11,12。(注:阿拉伯数字其实是古代印度人发明的,后来由阿拉伯人传入欧洲,被欧洲人误称为阿拉伯数字。)

I - 1

V - 5

X - 10

L - 50

C - 100 

D - 500

M - 1000

1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;

2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;

3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;

4、正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)

5、在一个数的上面画一条横线,表示这个数扩大1000倍。

有几条须注意掌握:

1、基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。

2、不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。

3、V 和X 左边的小数字只能用Ⅰ。

4、L 和C 左边的小数字只能用X。

5、D 和M 左边的小数字只能用C。

而这道题好就好在没有让我们来验证输入字符串是不是罗马数字,这样省掉不少功夫。需要用到 HashMap 数据结构,来将罗马数字的字母转化为对应的整数值,因为输入的一定是罗马数字,那么只要考虑两种情况即可:

第一,如果当前数字是最后一个数字,或者之后的数字比它小的话,则加上当前数字。

第二,其他情况则减去这个数字。

解法一:

class Solution {
public:
    int romanToInt(string s) {
        int res = 0;
        unordered_map<char, int> m{{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
        for (int i = 0; i < s.size(); ++i) {
            int val = m[s[i]];
            if (i == s.size() - 1 || m[s[i+1]] <= m[s[i]]) res += val;
            else res -= val;
        }
        return res;
    }
};

我们也可以每次跟前面的数字比较,如果小于等于前面的数字,先加上当前的数字,比如 "VI",第二个字母 'I' 小于第一个字母 'V',所以要加1。如果大于的前面的数字,加上当前的数字减去二倍前面的数字,这样可以把在上一个循环多加数减掉,比如 "IX",我们在 i=0 时,加上了第一个字母 'I' 的值,此时结果 res 为1。当 i=1 时,字母 'X' 大于前一个字母 'I',这说明前面的1是要减去的,而由于前一步不但没减,还多加了个1,所以此时要减去2倍的1,就是减2,所以才能得到9,整个过程是 res = 1 + 10 - 2 = 9,参见代码如下:

解法二:

class Solution {
public:
    int romanToInt(string s) {
        int res = 0;
        unordered_map<char, int> m{{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
        for (int i = 0; i < s.size(); ++i) {
            if (i == 0 || m[s[i]] <= m[s[i - 1]]) res += m[s[i]];
            else res += m[s[i]] - 2 * m[s[i - 1]];
        }
        return res;
    }
};

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

(0)

相关推荐

  • 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(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(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(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

  • 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(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 

  • 将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

  • Python3.5实现的罗马数字转换成整数功能示例

    本文实例讲述了Python3.5实现的罗马数字转换成整数功能.分享给大家供大家参考,具体如下: 问题概述: 给定一个罗马数字 ,将罗马数字转换成整数. 如罗马数字I,II,III,IV,V分别代表数字 1, 2, 3, 4, 51,2,3,4,5. 首先要来了解一下罗马数字表示法,基本字符有 7 个:I.V.X.L.C.D.M,分别表示 1.5.10.50.100.500.1000. 在构成数字的时候,有下列规则: 1.相同的数字连写,所表示的数等于这些数字相加得到的数,如:III = 3: 2

  • 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"

  • javascript将浮点数转换成整数的三个方法

    Summary 暂时我就想到3个方法而已.如果读者想到其他好用方法,也可以交流一下 parseInt 位运算符 Math.floor Math.ceil Description 一.parseInt 1. 实例 parseInt("13nash");//13 parseInt("")// NaN parseInt("0xA") //10(十六进制) parseInt(" 13")//13 parseInt("070&

  • PHP中将字符串转化为整数(int) intval() printf() 性能测试

    背景.概述 早在Sql注入横行的前几年,字符串转化为整数就已经被列为每个web程序必备的操作了.web程序将get或post来的id.整数等值强制经过转化函数转化为整数,过滤掉危险字符,尽可能降低系统本身被Sql注入的可能性. 现如今,虽然Sql注入已经逐渐淡出历史舞台,但是,为了保证web程序的正常运行,减少出错概率,更好的保证用的满意度,我们同样需要将用户的不正确输入转化为我们所需要的. 转化方式 在PHP中,我们可以使用3种方式将字符串转化为整数. 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:

  • JavaScript将数据转换成整数的方法

    JavaScript提供将数值转成整数的方法parseInt,用于转换字符串数据"123",或者浮点数1.23. 复制代码 代码如下: parseInt("1");  // 1parseInt("1.2");  // 1parseInt("-1.2");  // -1parseInt(1.2);  // 1parseInt(0);  // 0parseInt("0");  // 0 但是这个parseInt

  • 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

随机推荐