zoukankan      html  css  js  c++  java
  • leetcode-13-罗马数字转整数

    问题:

    解:

    package com.example.demo;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class Test13 {
    
        /**
         * 罗马数字转整数
         * 罗马字符前边的都比后边的字符大,根据这个特点,设置两个指针,一个是当前current代表当前的数字,
         * 一个pre代表之前的那个数字,在累加的时候判断current和pre的大小,如果pre< current时,代表数字加错,将
         * pre减2次即可(减2次是因为,本来不应该加的数,加了,另一次是本来该减的,还是加了 )
         * 例如:IV
         * 错误的结果是:  1 + 5 = 6    ==>   1 不应该加,因为I和后边的V是一个数,后边又加了一个I   也就是加了两次I
         * 所以需要减掉两个I
         * 正确的结果: 4
         *
         * @param s
         * @return
         */
        public int romanToInt(String s) {
            Map<Character, Integer> map = new HashMap<>();
            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 res = 0;
            char[] chars = s.toCharArray();
            int pre = 1000;
            for (char c : chars) {
                Integer current = map.get(c);
                res += current;
                if (current > pre) {
                    res = res - pre * 2;
                }
                pre = current;
            }
            return res;
        }
    
        public static void main(String[] args) {
            Test13 t = new Test13();
            int i = t.romanToInt("MCMXCIV");
            System.out.println(i);
        }
    }
  • 相关阅读:
    Oracle-函数
    Oracle-存储过程
    Linux-文件系统概述
    Oralce-PL/SQL编程-游标
    Oracle -操作数据库
    Oralce常用系统函数
    SQL语言基础-基本概念
    Linux-进程管理
    Linux-用户管理
    shell里的IFS内置环境变量
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/11225933.html
Copyright © 2011-2022 走看看