LeetCode: #13 Roman Numerals to Integers (Java) [map not used]

Roman numerals contain the following seven characters: I, V, X, L, C, D and M.

字符          数值
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, the Roman numeral 2 is written as II, which means two parallel ones. 12 is written as XII, which means X + II. 27 is written as XXVII, which is XX + V + II. Normally, the small numbers in Roman numerals are to the right of the large numbers. But there are special cases, for example, 4 is not written as IIII, but IV. The number 1 is to the left of the number 5, and the number represented is equal to the number 4 obtained by subtracting the number 1 from the large number 5. Similarly, the number 9 is represented as IX. This special rule only applies to the following six cases: I can be placed to the left of V (5) and X (10) to represent 4 and 9. X can be placed to the left of L (50) and C (100) to represent 40 and 90. C can be placed to the left of D (500) and M (1000) to represent 400 and 900.

Given a Roman numeral, convert it to an integer. Ensure that the input is in the range of 1 to 3999.

answer:

罗马数字由 I,V,X,L,C,D,M 构成;
当一个小值在大值的左边,则减小值,如 IV=5-1=4;
当一个小值在大值的右边,则加小值,如 VI=5+1=6;
由上可知,右值永远为正,因此最后一位必然为正。

Since I have not yet come into contact with the study of Java data structures, map is not used, but a method is defined to reflect the integer represented by each character.

public int getValue(char ch) {
    
    
        switch(ch) {
    
    
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }

The for loop compares each character with the integer represented by the character to the right to add or subtract.

class Solution {
    
    
    public int romanToInt(String s) {
    
    
        int sum = 0;
        int preNum = getValue(s.charAt(0));
        for(int i = 1;i < s.length(); i ++) {
    
    
            int num = getValue(s.charAt(i));
            if(preNum < num) {
    
    
                sum -= preNum;
            } else {
    
    
                sum += preNum;
            }
            preNum = num;
        }
        sum += preNum;
        return sum;
    }
    
    public int getValue(char ch) {
    
    
        switch(ch) {
    
    
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_45621376/article/details/111866005