《leetCode》:Roman to integer

xiaoxiao2021-02-28  97

题目描述:

Given a roman numeral, convert it to an integer.

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

基本字符 I V X L C D M 相应的阿拉伯数字表示为 1 5 10 50 100 500 1000 1、相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3; 2、小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12; 3、小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9; 4、正常使用时、连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外); 5、在一个数的上面画一条横线、表示这个数扩大 1000 倍。 百度还给出了一些注意事项,如下: 有几条须注意掌握: 基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数的左边只能用一个; 不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个; V 和 X 左边的小数字只能用 Ⅰ; L 和 C 左边的小数字只能用X; D 和 M 左边的小数字只能用 C。 在编程实现中只需要考虑以上三点内容 solution:

public int romanToInt(String s) { int sum=0; if(s.indexOf("IV")!=-1){sum-=2;} if(s.indexOf("IX")!=-1){sum-=2;} if(s.indexOf("XL")!=-1){sum-=20;} if(s.indexOf("XC")!=-1){sum-=20;} if(s.indexOf("CD")!=-1){sum-=200;} if(s.indexOf("CM")!=-1){sum-=200;} char c[]=s.toCharArray(); int count=0; for(;count<=s.length()-1;count++){ if(c[count]=='M') sum+=1000; if(c[count]=='D') sum+=500; if(c[count]=='C') sum+=100; if(c[count]=='L') sum+=50; if(c[count]=='X') sum+=10; if(c[count]=='V') sum+=5; if(c[count]=='I') sum+=1; } return sum; } 以上

转载请注明原文地址: https://www.6miu.com/read-36900.html

最新回复(0)