zoukankan      html  css  js  c++  java
  • 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.

    链接:https://leetcode.com/problems/roman-to-integer/

    2/9/2017

    主要问题在不熟悉Java,举例:

    HashMap<char, integer> --> HashMap<Character, Integer>,

    String.length(), 与array的length不同

    String.charAt()

     1 public class Solution {
     2     public int romanToInt(String s) {
     3         HashMap<Character, Integer> dict = new HashMap<Character, Integer>();
     4         dict.put('I', 1);
     5         dict.put('V', 5);
     6         dict.put('X', 10);
     7         dict.put('L', 50);
     8         dict.put('C', 100);
     9         dict.put('D', 500);
    10         dict.put('M', 1000);
    11         int prevValue = 0;
    12         int result = 0;
    13         int curValue = 0;
    14 
    15         for(int i = 0; i < s.length(); i++) {
    16             curValue = dict.get(s.charAt(i));
    17             if (prevValue != 0 && prevValue < curValue) {
    18                 result = result + curValue - 2 * prevValue;
    19             }else {
    20                 result = result + curValue;
    21             }
    22             prevValue = curValue;
    23         }
    24         return result;
    25     }
    26 }

    还是要熟悉语言啊

  • 相关阅读:
    boost库:函数对象
    boost库:智能指针
    linux 查看和修改文件时间
    linux正则表达式
    UVA
    UVA
    UVA
    UVA
    UVA
    对JavaScript的认识?
  • 原文地址:https://www.cnblogs.com/panini/p/6384836.html
Copyright © 2011-2022 走看看