LeetCode -- Roman to Integer

本文介绍了一种将罗马数字转换为整数的有效算法。通过扫描字符串并利用几个关键变量来实现转换,确保了准确性和效率。适用于1到3999范围内的罗马数字。

Question: Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Analysis: 该问题是将输入的罗马数字的字符串转化为整数。 方法:从左到右依次扫描字符串,需要三个变量:temp记录分段数字, lastv表示刚刚扫描过的数字, curv表示当前正在扫描的数字。

1. 若lastv == curv,则记录变量加上当前字符;

2. 若lastv < curv,则当前字符减去记录变量记录下的值;

3.若lastv > curv,记录变量直接加到结果中。

Answer:

public class Solution {
        public int romanToInt(String s) {
        if(s == null || s.length() == 0)
            return 0;
        int sum = 0;
        int temp = charToInt(s.charAt(0));
        int lastv = temp;
        for(int i=1; i<s.length(); i++){
            char c = s.charAt(i);
            int curv = charToInt(c);
            
            if(lastv == curv)
                temp += curv;
            else if(lastv < curv){
                temp = curv - temp;
            } else {
                sum += temp;
                temp = curv;
            }
            lastv = curv;
        }
        sum += temp;
        return sum;
        
    }
    
    private int charToInt(char c) {
        // TODO Auto-generated method stub
        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;
        }
    }
}

 

转载于:https://www.cnblogs.com/little-YTMM/p/4776671.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值