• Roman to Integer


    根据罗马数的规则可以很容易写出:

     1 class Solution {
     2 public:
     3     int romanToInt(string s) {
     4        int a[4]={0},i=0;
     5        if(s[i]=='M')
     6        while(s[i]=='M') {a[0]++;i++;}
     7        if(s[i]=='C'||'D')
     8        {
     9            if(s[i]=='D') {a[1]=5;i++;}
    10            while(s[i]=='C') {a[1]++;i++;}
    11            if(s[i]=='D') {a[1]=4;i++;}
    12            else if(s[i]=='M') {a[1]=9;i++;}
    13        }
    14         if(s[i]=='X'||'L')
    15        {
    16            if(s[i]=='L') {a[2]=5;i++;}
    17            while(s[i]=='X') {a[2]++;i++;}
    18            if(s[i]=='L') {a[2]=4;i++;}
    19            else if(s[i]=='C') {a[2]=9;i++;}
    20        }
    21         if(s[i]=='I'||'V')
    22        {
    23            if(s[i]=='V') {a[3]=5;i++;}
    24            while(s[i]=='I') {a[3]++;i++;}
    25            if(s[i]=='V') {a[3]=4;i++;}
    26            else if(s[i]=='X') {a[3]=9;i++;}
    27        }
    28       return a[0]*1000+a[1]*100+a[2]*10+a[3];
    29        
    30 
    31     }
    32 };
    View Code

    但观察罗马数还会发现,它其实每位的数没有权重,直接由那个字符就可以得到那位的值。

    以下是从网上抄过来的:

     1 int romanToInt(string s) 
     2 {
     3     unordered_map<char, int> T = { { 'I' , 1 },
     4                                    { 'V' , 5 },
     5                                    { 'X' , 10 },
     6                                    { 'L' , 50 },
     7                                    { 'C' , 100 },
     8                                    { 'D' , 500 },
     9                                    { 'M' , 1000 } };
    10 
    11    int sum = T[s.back()];
    12    for (int i = s.length() - 2; i >= 0; --i) 
    13    {
    14        if (T[s[i]] < T[s[i + 1]])
    15        {
    16            sum -= T[s[i]];
    17        }
    18        else
    19        {
    20            sum += T[s[i]];
    21        }
    22    }
    23 
    24    return sum;
    25 }
    View Code
  • 相关阅读:
    JDBC
    过滤器
    Servlet-web.xml 常见配置
    Servlet-HttpSession接口
    Servlet-Cookie对象
    Servlet-HttpServlet对象
    kmp算法及应用
    线段树入门到自闭
    tarjan算法与拓扑排序
    马拉车模板
  • 原文地址:https://www.cnblogs.com/daocaorenblog/p/5217317.html
Copyright © 2020-2023  润新知