Last active
November 19, 2022 00:40
-
-
Save silvericarus/a7339b961000bd277dce22a8aa623ece to your computer and use it in GitHub Desktop.
C function that takes a string with the valid roman numerals (IVXLCDM) and return the integer that those numerals represent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| int romanToInt(char *s){ | |
| int i; | |
| int num; | |
| num = 0; | |
| i = 0; | |
| while(s[i] != '\0') | |
| { | |
| if(s[i] == 'I') | |
| { | |
| if(s[i + 1] == 'V') | |
| { | |
| num += 4; | |
| i += 2; | |
| } | |
| else if(s[i + 1] == 'X') | |
| { | |
| num += 9; | |
| i += 2; | |
| } | |
| else | |
| { | |
| num += 1; | |
| i++; | |
| } | |
| } | |
| else if(s[i] == 'X') | |
| { | |
| if(s[i + 1] == 'L') | |
| { | |
| num += 40; | |
| i += 2; | |
| } | |
| else if(s[i + 1] == 'C') | |
| { | |
| num += 90; | |
| i += 2; | |
| } | |
| else | |
| { | |
| num += 10; | |
| i++; | |
| } | |
| } | |
| else if(s[i] == 'C') | |
| { | |
| if(s[i + 1] == 'D') | |
| { | |
| num += 400; | |
| i += 2; | |
| } | |
| else if(s[i + 1] == 'M') | |
| { | |
| num += 900; | |
| i += 2; | |
| } | |
| else | |
| { | |
| num += 100; | |
| i++; | |
| } | |
| } | |
| else if(s[i] == 'D') | |
| { | |
| num += 500; | |
| i++; | |
| } | |
| else if(s[i] == 'M') | |
| { | |
| num += 1000; | |
| i++; | |
| } | |
| else if(s[i] == 'L') | |
| { | |
| num += 50; | |
| i++; | |
| } | |
| else if(s[i] == 'V') | |
| { | |
| num += 5; | |
| i++; | |
| } | |
| } | |
| return(num); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment