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

    题目

    Given a roman numeral, convert it to an integer.

    Input is guaranteed to be within the range from 1 to 3999.

     题解

     这道题跟interger to roman一样都得先熟悉罗马数字的规则。罗马数字的规则我在integer to roman里面写了,可以参考那个。

    从后往前检查string,全局维护一个res来记录。

    代码如下:

     1 public static int romanToInt(String s) {
     2     int res = 0;
     3     for (int i = s.length() - 1; i >= 0; i--) {
     4         char c = s.charAt(i);
     5         if(c == 'I'){
     6             if(res >= 5)//如果>=5, 说明之前肯定遍历过V了,所以这个I肯定在左边,减
     7                 res += -1;
     8             else
     9                 res += 1;
    10         }else if(c == 'V'){//遇见V,L,D,M,统统都加5,50,500,100
    11             res += 5;
    12         }else if(c == 'X'){
    13             if(res >= 50)//说明肯定之前有过L,这个X肯定在左边,减
    14                 res += -10;
    15             else 
    16                 res += 10;
    17         }else if(c == 'L'){
    18             res += 50;
    19         }else if(c == 'C'){//说明之前有D,这个C肯定在左边,减。能被减的只有I X C
    20             if(res >= 500)
    21                 res += -100;
    22             else
    23                 res += 100;
    24         }else if(c == 'D'){
    25             res += 500;
    26         }else if(c == 'M'){
    27             res += 1000;
    28         }
    29     }
    30     return res;
    31 }

  • 相关阅读:
    如何提高沟通能力?
    如何做到科学决策?推荐你看这本《决策必读12篇》
    领导者如何让员工真心服从自己?
    MBA看什么书,MBA教材书目推荐
    有关战略管理的书,哪本最值得推荐?
    市场营销必看书籍推荐
    P1208 混合牛奶题解
    P5019 铺设道路题解
    P1728 陶陶摘苹果题解
    P1106 删数问题题解
  • 原文地址:https://www.cnblogs.com/springfor/p/3886477.html
Copyright © 2011-2022 走看看