• 13. Roman to Integer


    一、题目

      1、审题:

        

        2、分析:

          输入 1-3999 的罗马数字字符串,输出对应阿拉伯数字。

    二、解答

      1、分析:

        字符串从左至右开始计算字符对应的阿拉伯数字,

        若比相邻右一个字符所对应的数字大,则加上此字符对应数字;

        若比相邻右一个字符所对应的数字小,则减去此字符对应的数字;

      

    public class Solution {
        public int romanToInt(String s) {
             Map<String, Integer> map = new HashMap<String, Integer>();
            map.put("I", 1);
            map.put("V", 5);
            map.put("X", 10);
            map.put("L", 50);
            map.put("C", 100);
            map.put("D", 500);
            map.put("M", 1000);
            
            int ret = 0;
            for(int index = 0; index < s.length() - 1; index++) {
                if(map.get(s.charAt(index) + "") < map.get(s.charAt(index + 1) + "")) {
                    ret -= map.get(s.charAt(index) + "");
                }
                else {
                    ret += map.get(s.charAt(index) + "");
                }
            }
            ret += map.get(s.charAt(s.length()-1) + "");
            return ret;
        }
    }
  • 相关阅读:
    node体验
    JS练习--prototype的一道题目
    JS的OOP--继承之prototype
    JS的OOP--new一个function背后的实际操作
    JS中new运算符的运算顺序
    thymeleaf 拼接字符串与变量
    spring jpa exists
    LocalDateTime json格式化
    格式化java8 LocalDateTime
    springboot定时任务
  • 原文地址:https://www.cnblogs.com/skillking/p/9405081.html
Copyright © 2020-2023  润新知