9. Roman to Integer

Description:

Given a roman numeral, convert it to an integer.

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

Conversion Rule:

基本字符
I
V
X
L
C
D
M
相应的阿拉伯数字表示为
1
5
10
50
100
500
1000

  1. 1.相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
  2. 2.小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
  3. 3.小的数字(限于 I、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
  4. 4.正常使用时、连写的数字重复不得超过三次;

Solution:

1. How to split the String and express them to Integer ?

(1) String.toCharArray()

// return an array.

or

     String.charAt(int i)

     // according to the traversal, get the each Char.

(2) switch(String.char(int i)){

case 'M' :

num[I] = 1000;

break;

or

HashMap<Character, Integer> map = new HashMap<Character, Integer>();


2. How to calculate the result ?

If the left character's value is smaller than the right one, we should add the left one.

      If the left character's value is larger than the right one or this is the last character, we should subtract the left one.

      Therefore, we can use the top s.length-1 value to compare, and leave the last one to add only.


codes


import java.util.HashMap;

public class RomantoInteger {
    public static int romanToInt(String s){
        int[] nums = new int[s.length()];
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case 'M':
                    nums[i] = 1000;
                    break;
                case 'D':
                    nums[i] = 500;
                    break;
                case 'C':
                    nums[i] = 100;
                    break;
                case 'L':
                    nums[i] = 50;
                    break;
                case 'X':
                    nums[i] = 10;
                    break;
                case 'V':
                    nums[i] = 5;
                    break;
                case 'I':
                    nums[i] = 1;
                    break;
            }
        }
        int sum = 0;
        for (int i = 0; i < nums.length-1; i++){
            if (nums[i] >= nums[i+1]){
                sum += nums[i];
            }
            else {
                sum -= nums[i];
            }
        }
        return sum + nums[nums.length-1];
    }
}

Lesson learned:

1. String function

2. switch




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值