leetcode012:Integer to Roman
来源:互联网 发布:东方证券金典版软件 编辑:程序博客网 时间:2024/05/18 00:18
问题描述
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
问题分析
阿拉伯数字转罗马数字,只要了解了规则(请看参考链接,解释的很清晰),代码还是很简单的。范围是1到3999,所以千位单独处理,而个十百位的处理逻辑完全一致:0123、4、5678、9四类情况。
代码
class Solution {public: string intToRoman(int num) { string ans; int q = num / 1000;//千位 for (int i = 0; i < q; i++){ ans += 'M'; } q = num / 100 % 10;//百位 if (q == 9) ans += "CM"; else if (q >= 5){ ans += 'D'; for (int i = 0; i < q - 5; i++) ans += 'C'; } else if (q == 4) ans += "CD"; else { for (int i = 0; i < q; i++) ans += 'C'; } q = num / 10 % 10;//十位 if (q == 9) ans += "XC"; else if (q >= 5){ ans += 'L'; for (int i = 0; i < q - 5; i++) ans += 'X'; } else if (q == 4) ans += "XL"; else { for (int i = 0; i < q; i++) ans += 'X'; } q = num % 10;//个位 if (q == 9) ans += "IX"; else if (q >= 5){ ans += 'V'; for (int i = 0; i < q - 5; i++) ans += 'I'; } else if (q == 4) ans += "IV"; else { for (int i = 0; i < q; i++) ans += 'I'; } return ans; }};
0 0
- leetcode012:Integer to Roman
- leetcode012 Integer to Roman
- Leetcode012 Integer to Roman
- 【LeetCode012算法/编程练习C++】Integer to Roman //map的遍历&数组的妙用
- Integer to Roman & Roman to Integer
- Integer to Roman & Roman to Integer
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- Integer to Roman and Roman to Integer
- LeetCode Integer to Roman & Roman to Integer
- Roman to Integer/Integer to Roman
- leetcode - roman to integer & integer to roman
- "Roman to Integer" and "Integer to Roman"
- Roman to Integer &&Integer to Roman
- Roman to Integer and Integer to Roman
- Roman to Integer/Integer to Roman
- 一个故事告诉你比特币的原理及运作机制
- visio2013 页面太小怎么办
- 定义宏交换
- 【lambda】cocos 封闭函数局部变量lambda
- 分享45个android实例源码,很好很强大.收藏吧!!!
- leetcode012:Integer to Roman
- 在ubuntu上安装weka
- 关于adb server is out of date的问题
- Android Activity为什么要细化出onCreate、onStart、onResume、onPause、onStop、onDesdroy这么多方法让应用去重载?
- c++刷题一
- 《启示录-打造用户喜爱的产品》-第一部分
- JavaSE 拾遗(2)——JavaSE 面向对象程序设计语言基础(2)...变量
- python基础语法2(数据结构)
- 华为机试数字倒序