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.

题目思路

代码 C++

  • 思路一、
    1,前一个字符比后一个字符大,则前一个字符数值直接累加
    2,前一个字符比后一个字符小,则后一个字符数值减去前一个字符数值
class Solution {
public:
    int romanToInt(string s) {
        map<char, int> mp={{'I',1}, {'V', 5},{'X', 10}, {'L', 50},{'C',100}, {'D',500}, {'M',1000}};
        int result = 0;
        int i = 0;
        while(i < s.size()){
            if(mp[s[i]] < mp[s[i+1]]){
                result = result + mp[s[i+1]] - mp[s[i]];
                i = i + 2;
            }
            else{
                result = result + mp[s[i]];
                i = i + 1;
            }       
        }
        return result;
    }
};

总结展望

  • 发现大厂字符串考察的挺多的啊
  • 做春招笔试题发现自己字符串不行,今天开始补补吧
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,168评论 0 10
  • 13 Roman to Integer 罗马数字转整数 Description:Roman numerals ar...
    air_melt阅读 2,895评论 1 1
  • 很多人排斥小鲜肉,说他们没有演技,只会演空洞俗套的偶像剧,这无可厚非,无论哪一个行业,唱戏的还是打拳的卖药的,新人...
    百事可乐啦阅读 4,112评论 0 1
  • 分享,要每天反省 今天一早参加C主管的晨会,会上他跟组员提出三个问题: 1.目前团队中存在哪些问题? 2.自身存在...
    Dolas阅读 1,270评论 0 0
  • 人生又苦又短!又累又艰难!每个人的人生都是不一样的!每个人都有自己的内心世界,但每个人也是有内心情绪的! ...
    Qunny阅读 3,462评论 0 1

友情链接更多精彩内容