博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
13. Roman to Integer【leetcode】
阅读量:4680 次
发布时间:2019-06-09

本文共 1878 字,大约阅读时间需要 6 分钟。

Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

1 public class Solution { 2      public int romanToInt(String s) { 3         if (s == null || s.length()==0) { 4                 return 0; 5         } 6         Map
m = new HashMap
(); 7 m.put('I', 1); 8 m.put('V', 5); 9 m.put('X', 10);10 m.put('L', 50);11 m.put('C', 100);12 m.put('D', 500);13 m.put('M', 1000);14 15 int length = s.length();16 int result = m.get(s.charAt(length - 1));17 for (int i = length - 2; i >= 0; i--) {18 if (m.get(s.charAt(i + 1)) <= m.get(s.charAt(i))) {19 result += m.get(s.charAt(i));20 } else {21 result -= m.get(s.charAt(i));22 }23 }24 return result;25 }26 }27 28 // 方法二29 public class Solution {30 /**31 * @param s Roman representation32 * @return an integer33 */34 public int romanToInt(String s) {35 // Write your code here36 int ans;37 char[] sc = s.toCharArray();38 ans = toInt(sc[0]); //0 special39 for (int i = 1; i < s.length(); i++) {40 ans += toInt(sc[i]);41 if (toInt(sc[i - 1]) < toInt(sc[i])) {42 ans -= toInt(sc[i - 1]) * 2;43 }44 }45 return ans;46 }47 48 int toInt(char s) {49 switch(s) {50 case 'I':return 1;51 case 'V':return 5;52 case 'X':return 10;53 case 'L':return 50;54 case 'C':return 100;55 case 'D':return 500;56 case 'M':return 1000;57 }58 return 0;59 }60 }

 

转载于:https://www.cnblogs.com/haoHaoStudyShare/p/7308619.html

你可能感兴趣的文章