Created
January 1, 2017 20:24
-
-
Save oisincar/e61cc2ee0647d6bd574d0ece492cf2c5 to your computer and use it in GitHub Desktop.
This file contains 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
// Program to convert to roman numerals. | |
// | |
// I'm going to split the number into digits, and call a function to | |
// convert each one to roman numerals individually. | |
#include <string> | |
#include <iostream> | |
using namespace std; | |
string ConvertDigit(int digit, char one, char five, char ten); | |
int main() { | |
int n; | |
cin >> n; | |
string s = ConvertDigit((n/1000)%10, 'M', ' ', ' ') | |
+ ConvertDigit((n/100)%10, 'C', 'D', 'M') | |
+ ConvertDigit((n/10)%10, 'X', 'L', 'C') | |
+ ConvertDigit(n%10, 'I', 'V', 'X'); | |
cout << s << endl; | |
} | |
string ConvertDigit(int digit, char one, char five, char ten) { | |
// handle 4 and 9; | |
if (digit == 4) { | |
return string() + one + five; | |
} | |
if (digit == 9) { | |
return string() + one + ten; | |
} | |
string res; | |
// treat 0-3 and 5-8 cases as the same. | |
if (digit >= 5) { | |
res += five; | |
digit -= 5; | |
} | |
// append the correct number of ones. | |
for (int i = 0; i < digit; i++) { | |
res += one; | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment