leetcode 罗马数字与整数的转换算法
2018-03-31 14:34
549 查看
介绍:
该算法是将罗马数字转换为整数,思路如下:比如IXX,使用临时变量temp保存上一个已经遍历的罗马数字,比如:遍历时是从后往前遍历的:1> 刚开始时,temp = 0; 遍历当前遍历到第一个X,则temp == 0 < 10 == X ,则res = 10;temp = 10;2> 继续向前遍历,又遇到X,此时temp == 10 = 10 == X,则 res = res + 10;即res = 20; temp = 10;3> 继续向前遍历,遇到I,此时temp == 10 > 1 == I; 则 res = res - 1; 即res = 19; temp = 1;循环终止;
代码:
代码:
整数转罗马数字
该算法是将罗马数字转换为整数,思路如下:比如IXX,使用临时变量temp保存上一个已经遍历的罗马数字,比如:遍历时是从后往前遍历的:1> 刚开始时,temp = 0; 遍历当前遍历到第一个X,则temp == 0 < 10 == X ,则res = 10;temp = 10;2> 继续向前遍历,又遇到X,此时temp == 10 = 10 == X,则 res = res + 10;即res = 20; temp = 10;3> 继续向前遍历,遇到I,此时temp == 10 > 1 == I; 则 res = res - 1; 即res = 19; temp = 1;循环终止;
代码:
public class Solution { // 基本思想是根据罗马数字的特征,即左加右减的规律, 比如IX = 9, XI =11 public int romanToInt(String s){ if(s==null||s.length()<1) return -1; char ch[]=s.toCharArray(); HashMap<Character,Integer> hm=new HashMap<Character,Integer>(); hm.put('I', 1); hm.put('V', 5); hm.put('X', 10); hm.put('L', 50); hm.put('C', 100); hm.put('D', 500); hm.put('M', 1000); int res=0; int temp=0; 临时变量,保存的是当前遍历的上一个数值的值 int value=0; 当前罗马值的大小 for(int i=ch.length-1;i>=0;i--){ value=hm.get(ch[i]); if(temp<=value){ 左加 res+=value; temp=vlaue; }else{ 右减 res-=value; temp=value; } } return res; }
代码:
int romanToInt(string s) { int tagVal[256]; tagVal['I'] = 1; tagVal['V'] = 5; tagVal['X'] = 10; tagVal['C'] = 100; tagVal['M'] = 1000; tagVal['L'] = 50; tagVal['D'] = 500; int val = 0; for(int i = 0; i < s.length(); i++){ if(i+1 >= s.length() || tagVal[s[i+1]] <= tagVal[s[i]]) val += tagVal[s[i]]; else val -= tagVal[s[i]]; } return val; }
整数转罗马数字
string intToRoman(int num) { if(num <= 0) return ""; string ret = ""; static int number[13] = {1000, 900, 500, 400, 100,90, 50, 40, 10, 9, 5, 4, 1}; static string flags[13] = {"M","CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; for(int i = 0; i < 13 && num > 0; i++){ if(num < number[i]) continue; // cout<< i << " " << number[i] << " - " <<flags[i] << endl; while(num >= number[i]){ num-= number[i]; ret += flags[i]; } } return ret; }
相关文章推荐
- leetcode 罗马数字与整数的转换算法
- [C++]LeetCode 12: Integer to Roman(将整数转换为罗马数字)
- 【LeetCode-面试算法经典-Java实现】【013-Roman to Integer (罗马数字转成整数)】
- leetcode-12. Integer to Roman(整数转换成罗马数字)
- 简单的算法问题6——罗马数字转换成整数
- LeetCode习题笔记——罗马数字和整数之间的转换
- LeetCode | Integer to Roman(整数转换成罗马数字)
- leetcode:Integer to Roman(整数转化为罗马数字)
- 计蒜客 难题题库 014 罗马数字转换成整数
- 整数转换成罗马数字 python
- Leetcode 13 Roman to Integer 罗马数字转整数
- 计蒜客 第13题:整数转换成罗马数字
- 对一个罗马数字与阿拉伯数字转换算法的分析
- 计蒜客 -- 整数转换成罗马数字
- 从键盘输入某个十进制小数或整数,转换成对应的二进制小数并输出。 (查询十进制小数转换成二进制小数的算法,使用循环来实现。 最多保留小数位后7位数字即可)算法
- 第13题:整数转换成罗马数字
- python|计蒜客——整数转换成罗马数字
- [LeetCode] 13. Roman to Integer 罗马数字转为整数
- 整数转换成罗马数字
- c++ 计蒜客第13题整数转换为罗马数字