Created
October 10, 2012 02:36
-
-
Save ograycode/3862824 to your computer and use it in GitHub Desktop.
Roman Numeral To Number Converter
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
| #include "stdafx.h" | |
| #include <string> | |
| #include <iostream> | |
| #include <map> | |
| int romToNum(std::string rom); | |
| bool ShouldSubtract(std::string rom, int position); | |
| std::map<char, int> romNumMap; | |
| int _tmain(int argc, _TCHAR* argv[]) | |
| { | |
| romNumMap['I'] = 1; | |
| romNumMap['V'] = 5; | |
| romNumMap['X'] = 10; | |
| romNumMap['L'] = 50; | |
| romNumMap['C'] = 100; | |
| romNumMap['D'] = 500; | |
| romNumMap['M'] = 1000; | |
| bool shouldContinue = true; | |
| while (shouldContinue) | |
| { | |
| std::cout << "Enter a valid roman numeral\n"; | |
| std::string input; | |
| std::cin >> input; | |
| int converted = romToNum(input); | |
| std::cout << "Answer is: " << converted << "\n"; | |
| std::cout << "Another? [y/n]\n"; | |
| std::cin >> input; | |
| ('y' == input[0]) ? shouldContinue = true : shouldContinue = false; | |
| } | |
| return 0; | |
| } | |
| int romToNum(std::string rom) | |
| { | |
| int answer = 0; | |
| for (int y = 0; y < rom.size(); y++) | |
| { | |
| ShouldSubtract(rom, y) ? answer -= romNumMap[rom[y]] : answer += romNumMap[rom[y]]; | |
| } | |
| return answer; | |
| } | |
| bool ShouldSubtract(std::string rom, int position) | |
| { | |
| if (position+1 > rom.size()) | |
| return false; | |
| return (romNumMap[rom[position]] < romNumMap[rom[position+1]]) ? true : false; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment