LeetCode: Integer to Roman

这题因为不知道罗马数是怎么一回事。。就去网上找了答案

 1 class Solution {

 2 public:

 3     string intToRoman(int num) {  

 4       // Start typing your C/C++ solution below  

 5       // DO NOT write int main() function    

 6       char symbol[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};

 7       int scale = 1000;

 8       string ret;

 9       for (int i = 6; i >= 0; i -= 2) {

10           int digit = num / scale;

11           if (digit != 0) {

12               if (digit <= 3) ret = ret + string(digit, symbol[i]);

13               else if (digit == 4) ret = ret + symbol[i] + symbol[i+1];

14               else if (digit == 5) ret = ret + symbol[i+1];

15               else if (digit <= 8) ret = ret + symbol[i+1] + string(digit-5, symbol[i]);

16               else if (digit == 9) ret = ret + symbol[i] + symbol[i+2];

17           }

18           num %= scale;

19           scale /= 10;

20       }

21       return ret;

22     }  

23 };

 C#

 1 public class Solution {

 2     public string IntToRoman(int num) {

 3         char[] sym = new char[7]{'I', 'V', 'X', 'L', 'C', 'D', 'M'};

 4         int scale = 1000;

 5         string ans = "";

 6         for (int i = 6; i >= 0; i-=2) {

 7             int digit = num / scale;

 8             if (digit != 0) {

 9                 if (digit <= 3) ans  = ans + new string(sym[i], digit);

10                 else if (digit == 4) ans = ans + sym[i] + sym[i+1];

11                 else if (digit == 5) ans = ans + sym[i+1];

12                 else if (digit <= 8) ans = ans + sym[i+1] + new string(sym[i], digit-5);

13                 else if (digit == 9) ans = ans + sym[i] + sym[i+2];

14             }

15             num %= scale;

16             scale /= 10;

17         }

18         return ans;

19     }

20 }
View Code

 

你可能感兴趣的:(LeetCode)