[LeetCode]Roman to Integer

题目描述

Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.
给你一个罗马数字,将其转换成一个整数。输入保证在范围1-3999之间。

解题思路

        罗马数字基本字符:
  I、V、X、L、C、D、M

  相应的阿拉伯数字表示为:
  1.5、10、50、100、500、1000
  (1)相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
  (2)小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
  (3)小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
  (4)正常使用时连写的数字重复不得超过三次。(表盘上的四点钟--“IIII”,例外。)
  (5)在一个数的上面画一条横线,表示这个数增值1000 倍。

      不难发现,罗马数字其为纯粹叠加而成的,所以用户输入一个数后,我们可以来遍历这个数,用sum来总计和,比较i和i+1即可得出规律。

代码

public class Solution {
    public int romanToInt(String s) {
        if(s.length() < 1) return 0;
        int sum = 0;
        int sub = getRomanValue(s.charAt(0));
        int lastInt = sub;
        for(int i = 1;i < s.length();i++){
            char curC = s.charAt(i);
            int curInt = getRomanValue(curC);
            
            if(curInt < lastInt){
                sum += sub;  
                sub = curInt; 
            } else if(curInt > lastInt){
                sub = curInt - sub;
            } else if(curInt == lastInt){
                 sub += curInt;  
            }
            lastInt = curInt;
        }
        sum += sub;  
        return sum; 
    }
    
    public int getRomanValue(char c) {  
        switch(c) {  
            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;  
        }  
    }  
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值