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.

    解法:

      只要考虑两种情况即可:

        第一,如果当前数字是最后一个数字,或者之后的数字比它小的话,则加上当前数字
        第二,其他情况(即为4或者9,这种情况下才可能出现后面的罗马数字比前面的大),则减去这个数字
    public class Solution {
        public int romanToInt(String s) {
            if (s == null || s.length() == 0) return 0;
            
            int res = 0;
            HashMap<Character, Integer> map = new HashMap<>();
            map.put('M', 1000);
            map.put('D', 500);
            map.put('C', 100);
            map.put('L', 50);
            map.put('X', 10);
            map.put('V', 5);
            map.put('I', 1);
            
            for (int i = 0; i < s.length() - 1; i++) {
                if (map.get(s.charAt(i)) >= map.get(s.charAt(i + 1))) {
                    res += map.get(s.charAt(i));
                } else {
                    res -= map.get(s.charAt(i));
                }
            }
            res += map.get(s.charAt(s.length() - 1));
            
            return res;
        }
    }
  • 相关阅读:
    Mac上如何用命令行修改proxy设置
    Mac上解决访问github慢问题
    Bootstrap布局
    ListView详解
    sql server命名规范
    表的管理与操作
    常用编程技巧和方法
    有联系的jQuery选择器
    sql基础查询语句
    数值特征
  • 原文地址:https://www.cnblogs.com/strugglion/p/6404023.html
Copyright © 2011-2022 走看看