码迷,mamicode.com
首页 > 其他好文 > 详细

12. 整数转罗马数字

时间:2020-03-15 18:59:56      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:style   tor   bsp   arch   col   search   string   class   int   

 1 //用到了贪心思想
 2 class Solution 
 3 {
 4 public:
 5     int a[13] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
 6     string b[13] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
 7 public:
 8     //找到第一个小于等于num的数
 9     int bsearch_2(int l, int r ,int num)
10     {
11         while (l < r)
12         {
13             int mid = l + r + 1 >> 1;
14             if (a[mid] <= num) l = mid;
15             else r = mid - 1;
16         }
17         return l;
18     }
19     string intToRoman(int num) 
20     {
21         int l = 0, r = 12;
22         string res;
23         while(num)
24         {
25             int index = bsearch_2(l,r,num);
26             num -= a[index];
27             res += b[index];
28         }
29         return res;
30     }
31 };

 

12. 整数转罗马数字

标签:style   tor   bsp   arch   col   search   string   class   int   

原文地址:https://www.cnblogs.com/yuhong1103/p/12499118.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!