Roman to Integer, Leetcode 解题笔记

Given a roman numeral, convert it to an integer.

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

遍历给定String s中的字符,在总数中加上每个字符代表的数字,如果字符比上一个字符所代表的数字大,则在总数中减去两倍的上一个字符所代表的数字。

public class Solution {
    public int romanToInt(String s) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int[] a = {1000,500,100,50,10,5,1};
        char[] r = {'M','D','C','L','X','V','I'};
        int ret = 0;
        int index = 0;
        int last = 0;
        
        for(int i = 0; i < s.length(); i++){
            for(int j = 0; j < r.length; j++){
                if(r[j] == s.charAt(i)){
                    ret = ret + a[j];
                    if(last > j){
                        ret = ret - 2*a[last];
                    }
                    last = j;
                }
            }
        }
        return ret;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s