LeetCode【13】

1. Topic

Here Insert Picture Description
It is a simple question

2. Ideas

Solving simple and crude, characters traverse channeling occurs 'I' on a plus appears 'V' to plus 5, appear 'X' to plus 10, and so on. Look at the characters appear in channeling IV appears to minus 2, minus 2 would appear IX, XL appears to minus 20, minus 20 would appear XC, under two minus 200. The basis of this is expressed as 4 IV only once, he expressed IX 9 will only appear once. . .

3. Mapping punch

Here Insert Picture Description
Paste the code

class Solution {
    public int romanToInt(String s) {
        int val = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case 'I':
                    val++;
                    break;
                case 'V':
                    val += 5;
                    break;
                case 'X':
                    val += 10;
                    break;
                case 'L':
                    val += 50;
                    break;
                case 'C':
                    val += 100;
                    break;
                case 'D':
                    val += 500;
                    break;
                case 'M':
                    val += 1000;
                    break;
            }
        }
        if (s.contains("IV")) {
            val -= 2;
        }
        if (s.contains("IX")) {
            val -= 2;
        }
        if (s.contains("XL")) {
            val -= 20;
        }
        if (s.contains("XC")) {
            val -= 20;
        }
        if (s.contains("CD")) {
            val -= 200;
        }
        if (s.contains("CM")) {
            val -= 200;
        }
        return val;
    }
}

Guess you like

Origin blog.csdn.net/u012385160/article/details/89251229