zoukankan      html  css  js  c++  java
  • LeetCode 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 public class Solution {
     2     public int romanToInt(String s) {
     3         int res=0;
     4         HashMap<String, Integer> map = new HashMap<String, Integer>();
     5         map.put("M", 1000);map.put("CM", 900);map.put("D", 500);map.put("CD", 400);
     6         map.put("C", 100);map.put("XC", 90);
     7         map.put("L", 50);map.put("XL", 40);map.put("X", 10);map.put("IX", 9);map.put("V", 5);
     8         map.put("IV", 4);map.put("I",1);
     9         if (s.equals("")) return 0;
    10         if (s.length()==1) return map.get(s);
    11         String ss;
    12         for (int i = 0; i < s.length(); i++) {
    13             if (i<s.length() - 1) {
    14                 ss = s.substring(i, i + 2);
    15             }else {
    16                 ss = s.substring(i, i + 1);
    17             }
    18 
    19             if (map.containsKey(ss)) {
    20                 res = res + map.get(ss);
    21                 ++i;
    22             } else {
    23                 ss = s.substring(i, i + 1);
    24                 res = res + map.get(ss);
    25             }
    26         }
    27         return res;
    28     }
    29 }
  • 相关阅读:
    智联招聘
    我的Linux以及软件配置(长期更新)
    关于Git的笔记
    PHP和HTML表单
    web学习笔记——CSS整理(一)
    新开通博客园
    Thinphp模板替换
    __APP__
    大步前行
    centos 7 添加环境变量
  • 原文地址:https://www.cnblogs.com/birdhack/p/4125408.html
Copyright © 2011-2022 走看看