Google算法题:M-罗马数字与整数互转
来源:互联网 发布:软件代理销售协议 编辑:程序博客网 时间:2024/05/22 17:01
罗马转整数
http://www.lintcode.com/zh-cn/problem/roman-to-integer/
给定一个罗马数字,将其转换成整数。
返回的结果要求在1到3999的范围内。
说明
什么是 罗马数字?
- https://en.wikipedia.org/wiki/Roman_numerals
- https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
- http://baike.baidu.com/view/42061.htm
样例
IV
-> 4
XII
-> 12
XXI
-> 21
XCIX
-> 99
public class Solution { /* * @param s: Roman representation * @return: an integer */ Map<Character, Integer> map = new HashMap<Character, Integer>(); public Solution(){ initRomanMap(); } //TC = O(n) public int romanToInt(String s) { if(s==null) return 0; int n = s.length(); int res=0; for(int i=0; i<n; i++){ int cur = map.get(s.charAt(i)); int follow = 0; if(i!=n-1) follow = map.get(s.charAt(i+1)); if(cur<follow){ res+=follow-cur; i++; }else{ res+=cur; } } return res; } public void initRomanMap(){ //SymbolIVXLCDM //Value 1510501005001,000 map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); }};
整数转罗马
http://www.lintcode.com/zh-cn/problem/integer-to-roman/#
给定一个整数,将其转换成罗马数字。
返回的结果要求在1-3999的范围内。
说明
什么是 罗马数字?
- https://en.wikipedia.org/wiki/Roman_numerals
- https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
- http://baike.baidu.com/view/42061.htm
样例
4
-> IV
12
-> XII
21
-> XXI
99
-> XCIX
更多案例,请戳 http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
public class Solution { /* * @param s: Roman representation * @return: an integer */ public String intToRoman1(int num) { StringBuffer res = new StringBuffer(""); int[] values = new int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1}; String[] romans = new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int n = values.length; for(int i=0; i<n; i++){ int k = num/values[i]; while(k>0){ res.append(romans[i]); k--; } num = num%values[i]; } return res.toString(); } public String intToRoman(int num) { String[] M = new String[]{"","M","MM","MMM"}; String[] C = new String[]{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; String[] X = new String[]{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; String[] I = new String[]{"","I","II","III","IV","V","VI","VII","VIII","IX"}; return M[num/1000]+C[num%1000/100]+X[num%1000%100/10]+I[num%1000%100%10]; } };
阅读全文
0 0
- Google算法题:M-罗马数字与整数互转
- leetcode 罗马数字与整数的转换算法
- Leetcode简单题罗马数字转整数
- LeetCode 罗马数字转整数
- 罗马数字转整数
- 整数转罗马数字
- LintCode:整数转罗马数字
- LintCode_419_罗马数字转整数
- LintCode_418_整数转罗马数字
- Lintcode 罗马数字转整数
- [Lintcode]罗马数字转整数
- lintcode -- 罗马数字转整数
- lintcode -- 整数转罗马数字
- Lingcode 整数转罗马数字
- 罗马数字转整数
- 整数转罗马数字-LintCode
- 罗马数字转整数-LintCode
- 罗马数字与阿拉伯数字互转
- 检查针孔摄像头
- firewalld,iptable
- HttpClient天气接口测试
- Qt宏Q_OBJECT展开记录
- 学习笔记TF045:人工智能、深度学习、TensorFlow、比赛、公司
- Google算法题:M-罗马数字与整数互转
- 17.nm
- JavaScript中的函数表达式
- 抽象类,接口,匿名对象
- Hibernate中简答的增删改查
- hdu 6156 Palindrome Function
- 最新版房贷计算器
- String str = new String("Hello");
- 图片懒加载库echo.js源码学习