leetcode_Roman to Integer

来源:互联网 发布:mac如何隐藏下面的菜单 编辑:程序博客网 时间:2024/06/07 01:07

描述:

Given a roman numeral, convert it to an integer.

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

思路:

1.就像脑筋急转弯一样,这一题还真的搞了好久,主要是没想明白思路,现在再回过头去看代码,显而易见,或许这才是制造和创造的区别吧

2.大致过程就是一个循环,当currentChar的量级小于nextChar的量级时,直接加上nextChar的量级和currentChar的量级之差即可,其它的情况直接加上currentChar的量级,罗马数字就类似字符串的形式

3.另:这也就是有计算机才可以这么算,这对普通人来说得多麻烦啊,罗马数字很啰嗦。

代码:

public int romanToInt(String s) {       char chArr[]={'I','V','X','L','C','D','M','i','v','x','l','c','d','m'};        int numArr[]={1,5,10,50,100,500,1000,1,5,10,50,100,500,1000};        HashMap<Character, Integer>map=new HashMap<Character, Integer>();        for(int i=0;i<chArr.length;i++ )        map.put(chArr[i], numArr[i]);        int j=0;        int strLen=s.length();        char curCh,nextCh;        int sum=0;        for(int i=0;i<strLen;i++)        {        curCh=s.charAt(i);        j=i+1;        if(j<strLen)        {        nextCh=s.charAt(j);        if(map.get(curCh)<map.get(nextCh))//如果当前字符所代表的权值小于下一个字符所代表的权值        {        sum+=map.get(nextCh)-map.get(curCh);        i=j;//一次循环跳过两个字符        }else {        sum+=map.get(curCh);}                }else {sum+=map.get(curCh);//判断最后的字符}                }        return sum;    }


0 0
原创粉丝点击