[leetcode 12] Integer to Roman
2016-03-05 16:11
369 查看
Question:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
分析:
此问题首先要了解罗马数字规则(详见C++分类中的文章《罗马数字转换成阿拉伯数字》)
根据规则可以知道,当4,5,9,40,50,90,400,500,900时候是比较特殊的,需要判断是否为这些数据。
两种方法:
1、暴力法,依次判断是1000 ,100,10,1的多少倍,然后在其中判断4,5,9等的位置;
2、将4,5,9等特殊数据也提前声明好罗马数字,然后依次判断是1000,900,500,400,100,90,50,40,10,9,5,4,1的多少倍即可。
代码如下:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
分析:
此问题首先要了解罗马数字规则(详见C++分类中的文章《罗马数字转换成阿拉伯数字》)
根据规则可以知道,当4,5,9,40,50,90,400,500,900时候是比较特殊的,需要判断是否为这些数据。
两种方法:
1、暴力法,依次判断是1000 ,100,10,1的多少倍,然后在其中判断4,5,9等的位置;
2、将4,5,9等特殊数据也提前声明好罗马数字,然后依次判断是1000,900,500,400,100,90,50,40,10,9,5,4,1的多少倍即可。
代码如下:
<span style="font-size:14px;">class Solution { public: string intToRoman(int num) { string res = ""; string data[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int value[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; int base = -1; for(int i = 0; i < 13; i++){ if((base = num/value[i]) != 0){ while(base-- != 0) res += data[i]; num %= value[i]; } } return res; //暴力法 //string res = ""; /* unordered_map<int,string> maps; maps[1] = "I"; maps[5] = "V"; maps[10] = "X"; maps[50] = "L"; maps[100] = "C"; maps[500] = "D"; maps[1000] = "M"; if(num < 1 || num > 3999) return res; if(num / 1000 != 0){ int cnt = num / 1000; for(int i = 0; i < cnt; ++i){ res += maps[1000]; } num %= 1000; } if(num / 100 != 0){ int cnt = num / 100; if(cnt < 4){ for(int i = 0; i < cnt; ++i){ res += maps[100]; } } else{ if(cnt == 4){ res += (maps[100] + maps[500]); } else{ if(cnt == 9){ res += (maps[100] + maps[1000]); } else{ int n = cnt - 5; res += maps[500]; for(int j = 0; j < n; ++j){ res += maps[100]; } } } } num %= 100; } if(num / 10 != 0){ int cnt = num / 10; if(cnt < 4){ for(int i = 0; i < cnt; ++i){ res += maps[10]; } } else{ if(cnt == 4){ res += (maps[10] + maps[50]); } else{ if(cnt == 9){ res += (maps[10] + maps[100]); } else{ int n = cnt - 5; res += maps[50]; for(int j = 0; j < n; ++j){ res += maps[10]; } } } } num %= 10; } int cnt = num; if(cnt < 4){ for(int i = 0; i < cnt; ++i){ res += maps[1]; } } else{ if(cnt == 4){ res += (maps[1] + maps[5]); } else{ if(cnt == 9){ res += (maps[1] + maps[10]); } else{ int n = cnt - 5; res += maps[5]; for(int j = 0; j < n; ++j){ res += maps[1]; } } } } return res;*/ } };</span>
相关文章推荐
- EBS-PAC成本更新事务处理
- [转载]NSString中判断中文,英文,数字
- lamp搭建discuz缺少依赖 mysqli_connect()
- 关于JavaBean
- 着弹点
- Pentaho从零单排之一(简介与安装)
- 20135316王剑桥Linux内核学习笔记
- hdu1455 dfs+剪枝
- c++ 广义表
- codeforces 631c
- poj1062——最短路Dijkstra
- 【翻译】Ext JS最新技巧——2016-3-4
- Oracle关于高速缓存区应用原理
- deepin下搭建自己的git服务器
- hdoj-1722切蛋糕
- 多线程死锁
- 需要优化软件UI,so 沉寂许久之后开始学习界面的课程,把文档直接贴过来自己试着翻译
- 干货锦集
- 引入jquery后js代码未执行
- 【翻译】Ext JS最新技巧——2016-3-4