• lc13 Roman to Integer


    lc13 Roman to Integer

    遇到那六种特殊情况分别-2,-20,-200,

    按照罗马数字的规则,每种只可能出现一次。所以只需要考虑一次,用indexOf()即可判断是否出现这几种特殊情况

    然后遍历s,按照每个字符的定义,加上value即可

     1 class Solution {
     2     public int romanToInt(String s) {
     3         int res = 0;
     4     
     5         if(s.indexOf("IV") != -1)
     6             res -= 2;
     7         if(s.indexOf("IX") != -1)
     8             res -= 2;
     9         if(s.indexOf("XL") != -1)
    10             res -= 20;
    11         if(s.indexOf("XC") != -1)
    12             res -= 20;
    13         if(s.indexOf("CD") != -1)
    14             res -= 200;
    15         if(s.indexOf("CM") != -1)
    16             res -= 200;
    17         
    18         
    19         for(char i : s.toCharArray()){
    20             if(i == 'I')
    21                 res += 1;
    22             if(i == 'V')
    23                 res += 5;
    24             if(i == 'X')
    25                 res += 10;
    26             if(i == 'L')
    27                 res += 50;
    28             if(i == 'C')
    29                 res += 100;
    30             if(i == 'D')
    31                 res += 500;
    32             if(i == 'M')
    33                 res += 1000;
    34         }
    35            
    36         
    37     
    38         
    39         return res;
    40     }
    41 }
  • 相关阅读:
    soap-学习
    Redis教程
    Java 不可变对象
    java volatile
    Go语言
    mongodb 基础语法
    Linux 命令大全
    Java json字符串对比
    sqlserver 数据库阻塞和死锁
    http 和 https 的区别
  • 原文地址:https://www.cnblogs.com/hwd9654/p/10966853.html
Copyright © 2020-2023  润新知