image.png

    1. public int romanToInt(String s) {
    2. int[] a = new int[26];
    3. a['I' - 'A'] = 1;
    4. a['V' - 'A'] = 5;
    5. a['X' - 'A'] = 10;
    6. a['L' - 'A'] = 50;
    7. a['C' - 'A'] = 100;
    8. a['D' - 'A'] = 500;
    9. a['M' - 'A'] = 1000;
    10. char prev = 'A';
    11. int sum = 0;
    12. for(char c : s.toCharArray()) {
    13. if(a[c - 'A'] > a[prev - 'A']) { //如果前面的比后面的值小
    14. sum = sum - 2 * a[prev - 'A'];
    15. }
    16. sum = sum + a[c - 'A'];
    17. prev = c;
    18. }
    19. return sum;
    20. }