Roman to Integer:转换罗马数字到阿拉伯数字

Given a roman numeral, convert it to an integer.

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

解释:罗马数字:

I:1

V:5

X:10

L:50

C:100

D:500

M:1000

比如:MCMLXX:1970

MDCLXVI:1666

思路:从高位到低位扫描

可将1970划分为

[M] [CM] [L] [X] [X],即每个段内都是非降序,程序上体现为当出现升序时,减去前一个数字,否则加上前一个数字

class Solution {
    public int measure(char c){
        if(c=='I'){
            return 1;
        }else if(c=='V'){
            return 5;
        }else if(c=='X'){
            return 10;
        }else if(c=='L'){
            return 50;
        }else if(c=='C'){
            return 100;
        }else if(c=='D'){
            return 500;
        }else if(c=='M'){
            return 1000;
        }
        return 0;
    }
    
    public int romanToInt(String s) {
        int sum = 0;
        int pre = 0;
        int temp = 0;
        for(int i = 0;i <s.length() ;i++){
            temp = measure(s.charAt(i));
            if(temp <= pre){
                sum += pre;
                pre = temp;
            }else{
                sum -= pre;
                pre = temp;
            }
        }
        sum += pre;
        return sum;
    }
}

最近做点简单的题,偷偷懒......




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值