Skip to content

Instantly share code, notes, and snippets.

@oisincar
Created January 1, 2017 20:24
Show Gist options
  • Save oisincar/e61cc2ee0647d6bd574d0ece492cf2c5 to your computer and use it in GitHub Desktop.
Save oisincar/e61cc2ee0647d6bd574d0ece492cf2c5 to your computer and use it in GitHub Desktop.
// 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