Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
意思就是:
给出一个罗马数字,返回其对应的整数 num( 0<=num<=3999)表示;
罗马数字范围从 0-->3999
罗马数字有:git
I | V | X | L | C | D | M |
---|---|---|---|---|---|---|
1 | 5 | 10 | 50 | 100 | 500 | 1000 |
CD=400
其中 C=100 , D=500
,此时须要的后一个罗马数字减去前面一个罗马数字,其余状况都是一直加的。代码以下:class Solution { public: int romanToInt(string s) { int idx=0,n=s.length(); if(s.length()<=0)return 0; string roman="IVXLCDM"; int nums[] ={1,5,10,50,100,500,1000}; int res=0; //idx=roman.find(s.at(0)); //if(idx<0||idx>6)return 0; //if(n==1){ //return nums[idx]; //} int num1,num2; idx=0; while(idx<n-1){ // 须要考虑 idx+1 的越界状况 num1=roman.find(s[idx]); num2=roman.find(s[idx+1]); if(num2>num1){ res=res+(nums[num2]-nums[num1]); idx+=2; }else{ res=res+nums[num1]; ++idx; } } if(n-1==idx){ //须要考虑可能剩下的最后一个罗马数字 num1=roman.find(s[n-1]); res+=nums[num1]; } return res; } };
MCMVI=1906
, 扫描 V
时 V>I
(在罗马数字中,如下同),因此直接加,结果为:6,扫描 M
也同样,结果为1006,接下来扫描到 C
,此时 C<M
,因此应是减去 C
,结果是906,最后再加 M
,获得结果:1906。要作的,只是记录下上一次的罗马数字。代码以下:class Solution { public: int romanToInt(string s) { if(s.length()<=0)return 0; string roman="IVXLCDM"; int nums[] ={1,5,10,50,100,500,1000}; int n=s.length(); int res=0, idx=n-1, pre=0, ndx; while(idx>=0){ ndx=roman.find(s[idx]); if(pre>ndx){ res-=nums[ndx]; }else{ res+=nums[ndx]; } pre=ndx; --idx; } return res; } };
IVXLCDM
,若是遍历到罗马数字 w ,则判断以前已经求出的数字 res 是否小于 w ,若是小于,则 加上 w :res=res+w
,不然减去 w 。缘由是:由于是从后向前遍历,因此咱们已经遍历出来的数字确定是会小于下一进位的数字的,好比 189 ,89再大,也没有100大!因此此算法使用的就是这种思想,一旦出现违法了这种状况,那就是出现了 4 或者 9 的状况。说明咱们加多了,那就要减去。说的可能比较很差彻底理解,看代码:class Solution { public: int romanToInt(string s) { int res = 0 ,n=s.length(); for (int i = n - 1; i >= 0; --i) { char c = s.at(i); switch (c) { case 'I': res += (res >= 5 ? -1 : 1); break; case 'V': res += 5; break; case 'X': res += 10 * (res >= 50 ? -1 : 1); break; case 'L': res += 50; break; case 'C': res += 100 * (res >= 500 ? -1 : 1); break; case 'D': res += 500; break; case 'M': res += 1000; break; } } return res; } };
同系列:LeetCodesOJhttp://www.cnblogs.com/lomper/tag/LeetCodesOJ/github