Leetcode刷题-罗马数字转整数

题目

https://leetcode-cn.com/problems/roman-to-integer/
Leetcode刷题-罗马数字转整数_第1张图片

代码

class Solution {
    public int romanToInt(String s) {
        char[] arr = s.toCharArray();
        int pre = 0;
        int result = 0;
        for (int i = 0; i < arr.length; i++) {
            int cur = getByChar(arr[i]);
            if (cur > pre) {
                result -= pre;
            } else {
                result += pre;
            }
            pre = cur;
        }
        return result + pre;
    }
    private int getByChar(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;
        }
        return 0;
    }
}

结果

Leetcode刷题-罗马数字转整数_第2张图片

你可能感兴趣的:(每日一题,leetcode)