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

    题目:
    LeetCode:13. Roman to Integer

    描述:

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

    题意为 给定一个罗马数字转换为整数(1-3999)输出。

    分析:

    1、分析 1-4000可能出现的符号
        { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" },
        { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" },
        { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" },
        { "", "M", "MM", "MMM" }
        MM > M > CM > DC > D > CD > C > XC >LX > L > XL > X > IX > VI > V > IV > I
    2、 1)总结现有规律, M D C L X V I这种基本符号的组合;
        2)多个连续相同字符,则为加上一倍的对应基数 M = 1000,MM = 2000;
        3)CM CD IX 类似字符 低权值数字在前,均为减去低权值基数 CD = 400 D = 500 CM = 900
        3)DC LX VI 类似字符 高权值数字在前,均为加上低权值基数 DC = 600 LX = 50 + 10 = 60
        4)低权值位于高权值数字前则需减去低权值对应基数,反之为加上。(低权值在前为特殊情况仅有 IX IV XL XC CD CM等六种情况);
    
    

    代码:

    int romanToInt(string s) {
        int nRes = 0;
        int nLen = s.length();
        for (int i = 0; i < nLen; ++i)
        {
            switch (s[i])
            {
            case 'M':
                nRes += 1000;
                break;
            case 'D':
                nRes += 500;
                break;
            case 'C':
                if (i + 1 < nLen && ('D' == s[i + 1] || 'M' == s[i + 1]))
                {
                    nRes -= 100;
                }
                else
                {
                    nRes += 100;
                }
                break;
            case 'L':
                nRes += 50;
                break;
            case 'X':
                if (i + 1 < nLen && ('L' == s[i + 1] || 'C' == s[i + 1]))
                {
                    nRes -= 10;
                }
                else
                {
                    nRes += 10;
                }
                break;
            case 'V':
                nRes += 5;
                break;
            case 'I':
                if (i + 1 < nLen && ('X' == s[i + 1] || 'V' == s[i + 1]))
                {
                    nRes -= 1;
                }
                else
                {
                    nRes += 1;
                }
                break;
            default:
                nRes = -1;
                return nRes;
            }
        }
        return nRes;
    }
    

    备注:

    和上一题int 转Roman配套的题目。

  • 相关阅读:
    Conversion to Dalvik format failed with error 1 解决方法
    android 简单的反编译
    android ant打包问题总结
    android Sdcard 不同系统映射
    android 好用的开源框架
    android ScrollView 与 ListView 冲突汇总
    android 关于ImageView无法显示过长图片
    android 微信分享api调用总结
    android 捕获线程出错 重启线程
    c++中的容器和string类
  • 原文地址:https://www.cnblogs.com/liuwfuang96/p/7061156.html
Copyright © 2011-2022 走看看