Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
一開始寫法
/*
I=1 V=5 X=10 L=50 C=100 D=500 M=1000
IV=4 IX=9 XL=40 XC=90 CD=400 CM=900
*/
int roman(char *s){
if(*s=='I')return 1;
if(*s=='V')return 5;
if(*s=='X')return 10;
if(*s=='L')return 50;
if(*s=='C')return 100;
if(*s=='D')return 500;
if(*s=='M')return 1000;
}
int romanToInt(char* s) {
if(*s=='\0')return 0;
int ans=0, size=0;
while(s[size]!='\0'){
if( s[size+1]!='\0' ){
if(s[size]=='I' && s[size+1]=='V' ){ans+=4;size+=2;}
if(s[size]=='I' && s[size+1]=='X' ){ans+=9;size+=2;}
if(s[size]=='X' && s[size+1]=='L' ){ans+=40;size+=2;}
if(s[size]=='X' && s[size+1]=='C' ){ans+=90;size+=2;}
if(s[size]=='C' && s[size+1]=='D' ){ans+=400;size+=2;}
if(s[size]=='C' && s[size+1]=='M' ){ans+=900;size+=2;}
}
if(s[size]!='\0'){
ans+=roman(s[size]);
size++;
}
}
return ans;
}
但是不會過
因為我這邊是用s[size] 是char的型態
不是char* 所以在傳到roman(char*)會壞掉
要嘛全部char* 或是全部改成char
但是這樣還是會錯 因為我沒考慮到XC會連續的情況
所以如果是XCXC
那第一次處理完XC 會直接以為是X 不會是XC
全部加else就好了
-----
/*
I=1 V=5 X=10 L=50 C=100 D=500 M=1000
IV=4 IX=9 XL=40 XC=90 CD=400 CM=900
*/
int roman(char s){
if(s=='I')return 1;
if(s=='V')return 5;
if(s=='X')return 10;
if(s=='L')return 50;
if(s=='C')return 100;
if(s=='D')return 500;
if(s=='M')return 1000;
}
int romanToInt(char* s) {
if(*s=='\0')return 0;
int ans=0, size=0;
while(s[size]!='\0'){
if(s[size]=='I' && s[size+1]=='V' ){ans+=4;size+=2;}
else if(s[size]=='I' && s[size+1]=='X' ){ans+=9;size+=2;}
else if(s[size]=='X' && s[size+1]=='L' ){ans+=40;size+=2;}
else if(s[size]=='X' && s[size+1]=='C' ){ans+=90;size+=2;}
else if(s[size]=='C' && s[size+1]=='D' ){ans+=400;size+=2;}
else if(s[size]=='C' && s[size+1]=='M' ){ans+=900;size+=2;}
else {ans+=roman(s[size]); size++;}
}
return ans;
}
-----------
網路上更好的寫法
因為4跟9 都是 後面比前面大
所以檢查這個就知道是不是4或9
int romanToInt(char* s) { int N=strlen(s); int map[26]={0}; map['I'-'A']=1; map['V'-'A']=5; map['X'-'A']=10; map['L'-'A']=50; map['C'-'A']=100; map['D'-'A']=500; map['M'-'A']=1000; // main loop int sum=0;
for(int i=0;i// check IV, IX, XL, XC, CD, CM if(i!=N-1){ int n=map[s[i]-'A']; int nn=map[s[i+1]-'A']; if(nsum+=(nn-n); i++; }else{ sum+=n; } }else sum+=map[s[i]-'A']; } return sum; }
沒有留言:
張貼留言