zoukankan      html  css  js  c++  java
  • leetcode-13-Roman to Integer

    题目描述:

    Roman numerals are represented by seven different symbols: IVXLCD 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: C = 100, L = 50, XXX = 30 and III = 3.
    

    Example 5:

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

     

    要完成的函数:

    int romanToInt(string s)

     

    说明:

    1、这道题给定一个字符串s,要求将字符串中的罗马数字转化为阿拉伯数字(十进制)显示出来,I/V/X/L/C/D/M分别表示1/5/10/50/100/500/1000,除此之外,还定义了两条规则,如下:

    大数字在左,小数字在右,比如VI表示6。

    如果小数字在左,大数字在右,那么它们的组合结果是大数字减去小数字,如IV,表示5-1=4,IX=10-1=9,CM=1000-100=900。

    2、明白了题意,我们可以逐个处理字符,如果该字符比下一个字符大或者相等,那么总数加上当前字符。

    如果该字符比下一个字符小,那么总数减去当前字符。

    代码如下:

        int romanToInt(string s) 
        {
            int sum=0,i=0,s1=s.size();
            vector<int>char2num={100,500,0,0,0,0,1,0,0,50,1000,0,0,0,0,0,0,0,0,5,0,10};//每个罗马字符减去67,作为index,得到的值就是相应的阿拉伯数字。
            while(i<s1-1)                                  //此处也可以使用map
            {
                if(char2num[s[i]-67]>=char2num[s[i+1]-67])
                    sum+=char2num[s[i]-67];
                else
                    sum-=char2num[s[i]-67];
                i++;
            }
            sum+=char2num[s[i]-67];//加上最后一个字符对应的阿拉伯数字
            return sum;
        }
    

    上述代码实测116ms,beats 44.21% of cpp submissions。

  • 相关阅读:
    分享一个利用HTML5制作的海浪效果代码
    3人从小公寓创业,到世界最大引擎公司,Unity创始人谈14年...
    决策树--从原理到实现
    使用行为树(Behavior Tree)实现游戏AI
    FSM(状态机)、HFSM(分层状态机)、BT(行为树)的区别
    相遇3000亿美金之巅,阿里腾讯战力与血值几何?
    深入浅出聊Unity3D项目优化:从Draw Calls到GC
    Unity性能优化专题---腾讯牛人分享经验
    高通创始人复盘30年发展历程
    Gym
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9064107.html
Copyright © 2011-2022 走看看