LeetCode - Integer to Roman

LeetCode - Integer to Roman

2013.12.1 22:56

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Solution:

  First of all, for those who lacks background knowledge of Roman numerals(including me), here is the wiki:

    http://en.wikipedia.org/wiki/Roman_numerals

  My solution is to get the result from the most significant digit to the lowest. The representation of each digit can be pre-defined and stored in a dictionary. We'll just concatenate the Roman representation for each digit to get the final result.

  Time complexity is O(lg(n)), where n is the input integer. Space complexity is O(lg(n)), actually 10 * lg(n).

Accepted code:

 1 //1CE, 1RE, 1WA, 1AC

 2 class Solution {

 3 public:

 4     string intToRoman(int num) {

 5         // IMPORTANT: Please reset any member data you declared, as

 6         // the same Solution instance will be reused for each test case.    

 7         string res;

 8         int a[4];

 9         

10         a[0] = num % 10;

11         num /= 10;

12         a[1] = num % 10;

13         num /= 10;

14         a[2] = num % 10;

15         num /= 10;

16         a[3] = num % 10;

17         num /= 10;

18         

19         res = "";

20         //2WA here..

21         /*

22         for(int i = 0; i < 4; ++i){

23             res += code[i][a[i]];

24         }

25         */

26         /*

27         for(int i = 3; i >= 0; ++i){

28             res += code[i][a[i]];

29         }

30         */

31         for(int i = 3; i >= 0; --i){

32             res += code[i][a[i]];

33         }

34         

35         return res;

36     }

37 private:

38     const string code[4][10] = {

39         {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},

40         {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},

41         {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},

42         {"", "M", "MM", "MMM", "", "", "", "", "", ""}

43     };

44 };

 

你可能感兴趣的:(LeetCode)