把具体的情况一个一个实现即可,没有什么幺蛾子。 代码 classSolution{publicintromanToInt(String s){intans=0;for(inti=0; i!=s.length(); ++i) {switch(s.charAt(i)) {case'I':if(i<s.length()-1&& (s.charAt(i+1)=='X'|| s.charAt(i+1)=='V')) {
因为最后一位字符后面再无其他字符,所以只能做加法。 publicstaticintromanToInt(String s){intresult =0; Map<Character, Integer> map =newHashMap<Character, 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);...
I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Input is guaranteed to be wi...
public class Solution { public int romanToInt(String s) { int total = charToInt(s.charAt(0)); for(int i = 1; i < s.length(); i++){ int prev = charToInt(s.charAt(i-1)); int curr = charToInt(s.charAt(i)); if(curr <= prev){ total += curr; } else { total = tot...
package javaLeetCode.primary; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Stack; public class RomanToInteger_13 { public static void main(String[] args) { System.out.println("Please input a roman numeral:"); ...
1968-array-with-elements-not-equal-to-average-of-neighbors.cpp 1980-find-unique-binary-string.cpp 1984-minimum-difference-between-highest-and-lowest-of-k-scores.cpp 1985-Find-The-Kth-Largest-Integer-In-The-Array.cpp 1985-find-the-kth-largest-integer-in-the-array.cpp 2001-number-of-pairs-of...
1963-minimum-number-of-swaps-to-make-the-string-balanced.cpp 1968-array-with-elements-not-equal-to-average-of-neighbors.cpp 1980-find-unique-binary-string.cpp 1984-minimum-difference-between-highest-and-lowest-of-k-scores.cpp 1985-Find-The-Kth-Largest-Integer-In-The-Array.cpp 1985-find-the-...
https://leetcode.com/problems/roman-to-integer/discuss/6509/7ms-solution-in-Java.-easy-to-understand 利用到罗马数字的规则,一般情况是表示数字大的字母在前,数字小的字母在后,如果不是这样,就说明出现了特殊情况,此时应该做减法。 privateintgetVal(charc){switch(c){case'M':return1000;case'D':return...
保证输入的数字范围在1 到 3999之间。 分析 都加起来,找出反作用的,减二倍。 java代码 publicclassSolution{publicintromanToInt(Strings){if(s==null||s.length()==0){return0;}intres=0;if(s.indexOf("CM")!=-1)res-=200;if(s.indexOf("CD")!=-1)res-=200;if(s.indexOf("XC")!=-1)res...
java: public int romanToInt(String s) { LinkedHashMap<String, Integer> roman = new LinkedHashMap< String,Integer>(); roman.put("I", 1); roman.put("V", 5); roman.put("X", 10); roman.put("L", 50); roman.put("C", 100); ...