leetcode-12

整数转罗马数字

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4         int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
 5         string reps[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
 6 
 7         string res;
 8         for (int i=0; i<13; i++)
 9         {
10             while (num >= values[i])
11             {
12                 num -= values[i];
13                 res += reps[i];
14             }
15         }
16         return res;
17     }
18 };

在向res中添加字符时,可以用 res += reps[i]来添加

posted @ 2024-08-23 20:58  路人呃呃  阅读(13)  评论(0)    收藏  举报