leetcode-algorithms-12 Integer to Roman

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.

X can be placed before L (50) and C (100) to make 40 and 90.

C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: 3
Output: "III"

Example 2:

Input: 4
Output: "IV"

Example 3:

Input: 9
Output: "IX"

Example 4:

Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

Example 5:

Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

解法

class Solution
{
public:
string intToRoman(int num)
{
int n[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string s[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; std::string roman;
int i = 0;
while(num != 0)
{
if (num >= n[i])
{
roman += s[i];
num -= n[i];
}
else
++i;
} return roman;
}
};

链接: leetcode-algorithms 目录

最新文章

  1. C语言中的++和--
  2. Excel 函数记录
  3. [SQL]CASE用户数据统计
  4. rel=nofollow
  5. [再寄小读者之数学篇](2014-11-19 $\sin x/x$ 在 $(0,\pi/2)$ 上递增)
  6. css03复合选择器
  7. nodejs定时任务node-schedule
  8. 前端资料QQ群交流
  9. HDU2276 - Kiki & Little Kiki 2(矩阵高速幂)
  10. OpenCV-Python教程(5、初级滤波内容)
  11. oracle学习 笔记(1)
  12. JavaScript学习笔记(十六)——面向对象编程
  13. Python爬虫-尝试使用人工和OCR处理验证码模拟登入
  14. Dynamics CRM 配置 OAuth 2.0
  15. Solve Error: "errcode": 40016, "errmsg": "invalid button size hint"
  16. 转://Window下安装Oracle ASM单实例数据库
  17. node.js(一)
  18. 脚本设置IP bat 命令行设置自动获取IP和固定IP
  19. memcached哈希表操作主要逻辑笔记
  20. 协变(covariance),逆变(contravariance)与不变(invariance)

热门文章

  1. js中属性点.和中括号[]的关系。
  2. python测试
  3. Echarts 地图上显示数值
  4. linux_nmon监控方法
  5. 项目Alpha冲刺——代码规范、冲刺任务与计划
  6. P4391 [BOI2009]Radio Transmission
  7. javascript 创建video元素
  8. PL/SQL Developer安装配置
  9. [原][粒子特效][spark]插值器interpolator
  10. [原][osgEarth][JSBSim]重新整理使用JSBSim飞机动力模拟的使用