12. 整数转罗马数字
Posted yuhong1103
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了12. 整数转罗马数字相关的知识,希望对你有一定的参考价值。
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. 整数转罗马数字的主要内容,如果未能解决你的问题,请参考以下文章