leetcode打卡day13

罗马数字转整数
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。

思路:小值放在大值左边就是减,大值放在小值左边就是加。

import java.util.*;
class Solution {
    public int romanToInt(String s) {
        int a=getValue(s.charAt(0)),sum=0;
        for(int i=1;i<s.length();i++){
            int num=getValue(s.charAt(i));
            if(a<num){
                sum=sum-a;
            }
            else {
                sum=sum+a;
            }
            a=num;
        }
        sum+=a;
        return sum;
    }
  private 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;
        }
  }

执行用时 :4 ms, 在所有 Java 提交中击败了99.97%的用户
内存消耗 :41 MB, 在所有 Java 提交中击败了5.01%的用户

发布了20 篇原创文章 · 获赞 2 · 访问量 280

猜你喜欢

转载自blog.csdn.net/weixin_46442834/article/details/104848178