Leetcode OJ 13 Roman to Integer [Easy]

题目描述:

Given a roman numeral, convert it to aninteger.

Input is guaranteed to be within the rangefrom 1 to 3999.

题目理解:

给定一个罗马数字(字符串的形式),将其转换成一个整数,范围是1到3999

分析:

1.    罗马数字1到10为:I,II,III,IV,V,VI,VII,VIII,IX,X

2.    I(1),V(5),X(10),L(50),C(100),D(500),M(1000)

3.    观察“左减右加”的规律,左边的字符代表l的数子比紧挨的右边r小,则该l代表-l;繁殖如果l>=r,代表+l

4.    从字符串的末尾开始到启始位置遍历字符串,如果当前的字符代表的数字比上一个小,则result -= 当前字符代表的数字;如果当前字符代表的数字>=上一个,则result += 当前字符代表的数字

解答:

public int romanToInt(String s) {
              Map<Character, Integer> charToInt = new HashMap<Character,Integer>();
              charToInt.put('I',1);
              charToInt.put('V',5);
              charToInt.put('X',10);
              charToInt.put('L',50);
              charToInt.put('C',100);
              charToInt.put('D',500);
              charToInt.put('M',1000);
              int result = 0;
             int pre = 0;
             int cur = 0;
              char[] nums = s.toCharArray();
              for(int i = s.length() - 1; i >= 0; i--){
                  cur = charToInt.get(nums[i]);
                  if(cur >= pre) result += cur;
                  else result -= cur;
                  pre = cur;
              }
               return result;

    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值