【LeetCode】13. Roman to Integer && 12. Integer to Roman
2016-03-09 09:56
337 查看
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
[罗马转整数]
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
【整数转罗马】
Input is guaranteed to be within the range from 1 to 3999.
[罗马转整数]
/* 1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 1000~3000: {"M", "MM", "MMM"}. */ class Solution { public: int toNum(char c) { switch(c){ case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; } return 0; } int romanToInt(string s) { int result = toNum(s[0]); int i; for(i=1; i < s.length(); i++) { if(toNum(s[i])<=toNum(s[i-1])){ result +=toNum(s[i]) ; } else if(toNum(s[i])>toNum(s[i-1])) { result +=toNum(s[i]) - 2*toNum(s[i-1]); } } return result; } };
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
【整数转罗马】
class Solution { public: string intToRoman(int num) { string s=""; string roman[4][10]={{"","I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, {"","C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, {"","M", "MM", "MMM"} }; int position = 0; while(0 < num) { s = roman[position][num%10] + s; position++; num = num / 10; } return s; } };
相关文章推荐
- Podfile 常见语法
- java中字符串/java对象<-->JSON对象互转
- MongoDB+MongoVUE安装及入门
- 【代码笔记】给背景图赋值颜色
- iOS Auto Layout 中的对齐选项
- Android设备间实现蓝牙共享上网
- 做出漂亮的网页表格(CSS代替bordercolorlight与bordercolordark)
- 【代码笔记】给背景图赋值颜色
- 4.8.8 安卓开发笔记——自定义广告轮播Banner(无限循环实现)
- Linux文件特殊权限
- 蓝桥杯 BASIC 24 龟兔赛跑预測(模拟)
- NYOJ128 前缀式计算 【栈】
- 2015软件设计论点总结
- 推荐一个CMMI认证查询网站
- C#的Lambda表达式嵌套例子
- 基于ZigBee和STM32的智能家居控制系统的设计与实现
- 企业如何利用软文推广做到风生水起的
- 逆向分析网络协议 iOS 篇
- Linux下的tar压缩解压缩命令详解
- 设计模式:外观模式