• Leetcode13>罗马数字转换为整数


     该算法是将罗马数字转换为整数,思路如下:比如IXX,使用临时变量temp保存上一个已经遍历的罗马数字,比如:
    遍历时是从后往前遍历的:
    1>  刚开始时,temp = 0; 遍历当前遍历到第一个X,则temp == 0 < 10 == X ,则res = 10;temp = 10;
    2> 继续向前遍历,又遇到X,此时temp == 10 = 10 == X,则 res = res + 10;即res = 20; temp = 10;
    3> 继续向前遍历,遇到I,此时temp == 10 > 1 == I; 则 res = res - 1; 即res = 19; temp = 1;
    循环终止;

    1
    public class Solution { 2 // 基本思想是根据罗马数字的特征,即左加右减的规律, 比如IX = 9, XI =11 3 public int romanToInt(String s) { 4 if(s == null || s.length() < 1) 5 return -1; 6 char[] ch = s.toCharArray(); 7 HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); 8 hm.put('I', 1); 9 hm.put('V', 5); 10 hm.put('X', 10); 11 hm.put('L', 50); 12 hm.put('C', 100); 13 hm.put('D', 500); 14 hm.put('M', 1000); 15 int res = 0; 16 int temp = 0; // 临时变量,保存的是当前遍历的上一个数值的值 17 int value = 0; // 当前罗马值的大小 18 for(int i = ch.length - 1; i >= 0; i--) 19 { 20 value = hm.get(ch[i]); 21 if(temp <= value) // 左加 22 { 23 res += value; 24 temp = value; 25 } 26 else // 右减 27 { 28 res -= value; 29 temp = value; 30 } 31 } 32 return res; 33 } 34 } 35   
  • 相关阅读:
    MySQL权限详解
    MySql 详解
    顶级Python库
    第一次读到就震撼的句子
    Windows快捷键大全
    Pycharm超级好用的快捷键——效率之王
    Django框架
    前端入门和进阶必会
    正则表达式BREs,EREs,PREs的比较
    selenium模块基础用法详解
  • 原文地址:https://www.cnblogs.com/leavescy/p/5864747.html
Copyright © 2020-2023  润新知