zoukankan      html  css  js  c++  java
  • [LeetCode][Java] 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, 罗马数字共同拥有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。

     * 罗马数字中没有“0”。

     * 2, 反复次数:一个罗马数字最多反复3次。

     * 3, 右加左减:

     * 在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。

     * 在较大的罗马数字的左边记上较小的罗马数字。表示大数字减小数字。


    AC代码:

    public class Solution
    {
        private  int sss;
    
        public  int romanToInt(String s)
        {
          Map<Character, Integer> dct=new HashMap<Character, Integer>() ;
          dct.put('I', 1); 
          dct.put('i', 1); 
          dct.put('V', 5); 
          dct.put('v', 5); 
          dct.put('X', 10); 
          dct.put('x', 10); 
          dct.put('L', 50); 
          dct.put('l', 50); 
          dct.put('C', 100); 
          dct.put('c', 100); 
          dct.put('D', 500); 
          dct.put('d', 500);
          dct.put('M', 1000); 
          dct.put('m', 1000); 
          int sum = 0, j;
          for(int i = 0; i < s.length(); ++i)
          {
              j = i+1;
              if(j < s.length() && dct.get(s.charAt(j)) > dct.get(s.charAt(i)))
              {
                sum += dct.get(s.charAt(j)) - dct.get(s.charAt(i));
                i = j;
              }
              else
                sum += dct.get(s.charAt(i));
          }
          return sum;
        }
    }


  • 相关阅读:
    wenbao与筛法素数及判断模板
    wenbao与dfs奇偶剪枝
    wenbao与搜索
    wenbao与反素数
    wenbao与三分
    wenbao与极角排序
    wenbao与差分约束
    wenbao与勒让德定理
    Zotero 导出参考文献列表
    为人性僻耽佳句(三)
  • 原文地址:https://www.cnblogs.com/wzjhoutai/p/7154363.html
Copyright © 2011-2022 走看看