zoukankan      html  css  js  c++  java
  • 【Leetcode-easy】Roman to Integer

    罗马数字转化为整数
    * 1、基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数的左边只能用一个;
    * 2、不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个;
    * 3、V 和 X 左边的小数字只能用 Ⅰ;
    * 4、L 和 C 左边的小数字只能用X;
    * 5、D 和 M 左边的小数字只能用 C。

    思路:顺序读取字符,如果前面后面一位大于前面一位,则减去2倍的前面一位,因为前面加过一次。否则加上该位对应的数字。

     1     public int romanToInt(String s) {
     2          int result=toNum(s.charAt(0));
     3          for(int i=1;i<s.length();i++){
     4              if(toNum(s.charAt(i-1))<toNum(s.charAt(i))){
     5                  result+=toNum(s.charAt(i))-2*toNum(s.charAt(i-1));    //为什么要减去2倍的前一位,是因为前面加过一次。可以分析 XIX=19;
     6              }else{
     7                  result+=toNum(s.charAt(i));
     8              }
     9          }
    10         return result;
    11     }
    12     int toNum(char ch){    //或是通过存储在HashMap中。
    13         int n=0;
    14         switch(ch){
    15             case 'I': return 1;
    16             case 'V': return 5;
    17             case 'X': return 10;
    18             case 'L': return 50;
    19             case 'C': return 100;
    20             case 'D': return 500;
    21             case 'M': return 1000;
    22         }
    23         return n;
    24     }
  • 相关阅读:
    Google Web 字体 API 访谈
    关于如何跨越抄袭程序阶段的一些断想
    DirectX开发中找不到dxtrans.h的问题的解决
    Google Web 字体 API 访谈
    NetBeans 6.9 发布后选版 1 已经可用
    Thrift java服务器与客户端示例
    Wing IDE Pro v. 4.1.91 Python Wingware Python IDE
    tkang's blog
    Thrift的简单使用
    maven加载自己的包
  • 原文地址:https://www.cnblogs.com/scecit/p/4978899.html
Copyright © 2011-2022 走看看