zoukankan      html  css  js  c++  java
  • [LeetCode]13、Roman to Integer

    题目描述:

    Given a roman numeral, convert it to an integer.

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

    思路:

    罗马数字转int   遍历string,如果左边大于右边,则加上右边,如果小于,则减去  用sum记录结果

     1 public class Solution13{
     2     public int romanToInt(String s){
     3         HashMap<Character, Integer> map = new HashMap<>();
     4         map.put('I', 1);
     5         map.put('V', 5);
     6         map.put('X', 10);
     7         map.put('L', 50);
     8         map.put('C', 100);
     9         map.put('D', 500);
    10         map.put('M', 1000);
    11         int sum = 0;
    12         
    13         for(int i = 0;i < s.length();i++){
    14             //int value = map.get(s.charAt(i));
    15             if(i == s.length()-1 || map.get(s.charAt(i+1))<=map.get(s.charAt(i))){
    16                 sum += map.get(s.charAt(i));
    17             }
    18             else {
    19                 sum -= map.get(s.charAt(i));    
    20             }
    21         }
    22         return sum;
    23     }
    24     public static void main(String[] args) {
    25         // TODO Auto-generated method stub
    26         Solution13 solution13 = new Solution13();
    27         System.out.println(solution13.romanToInt("XLVI"));
    28     }
    29 }
  • 相关阅读:
    函数中this指向问题及函数不同方式的调用
    拷贝继承
    组合继承
    借用构造函数
    继承
    UVA-11054(扫描法)
    hihocoder-1347 小h的树上的朋友(lca+线段树)
    UVA-10391(字符串检索)
    UVA-10125(中途相遇法)
    UVA-10827(前缀和降维)
  • 原文地址:https://www.cnblogs.com/zlz099/p/8144878.html
Copyright © 2011-2022 走看看