12. Integer to Roman
2018-03-14 05:33
323 查看
问题描述
Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.
题目链接:
思路分析
给一个1-3999的整数,将其转化为罗马数字的字符串。用一个极为丑陋的方式解决,将满足不同的条件的if语句放入循环中,每次减去相应的数值,直到num变为0;
代码
class Solution { public: string intToRoman(int num) { string result = ""; while (num != 0){ if (num >= 1000){ num -= 1000; result += "M"; continue; } if (num >= 900){ num -= 900; result += "CM"; continue; } if (num >= 500){ num -= 500; result += "D"; continue; } if (num >= 400){ num -= 400; result += "CD"; continue; } if (num >= 100){ num -= 100; result += "C"; continue; } if (num >= 90){ num -= 90; result += "XC"; continue; } if (num >= 50){ num -= 50; result += "L"; continue; } if (num >= 40){ num -= 40; result += "XL"; continue; } if (num >= 10){ num -= 10; result += "X"; continue; } if (num == 9){ num -= 9; result += "IX"; continue; } if (num >= 5){ num -= 5; result += "V"; continue; } if (num == 4){ num -= 4; result += "IV"; continue; } if (num >= 1){ num -= 1; result += "I"; continue; } } return result; } };
时间复杂度:O(logn)
空间复杂度:O(1)
反思
看到一样丑陋的代码我就放心了,但是人家的方法还是比我巧妙的,把每一种的情况都考虑到了。class Solution { public: const static string THOUS[]; const static string HUNDS[]; const static string TENS[]; const static string ONES[]; string intToRoman(int num) { string result; result += THOUS[(int)(num/1000)%10]; result += HUNDS[(int)(num/100)%10]; result += TENS[(int)(num/10)%10]; result += ONES[num%10]; return result; } }; const string Solution::THOUS[] = {"","M","MM","MMM"}; const string Solution::HUNDS[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; const string Solution::TENS[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; const string Solution::ONES[] = { a355 "","I","II","III","IV","V","VI","VII","VIII","IX"};
相关文章推荐
- 12-Integer to Roman
- [Leetcode] 12. Integer to Roman
- 12:Integer to Roman(数字转为罗马数字)
- leetcode 12 ,13 Integer to Roman &&Roman to Integer 罗马与阿拉伯数组转换
- LeetCode 12. Integer to Roman
- [Leetcode]_12 Integer to Roman
- LeetCode OJ 12 Integer to Roman
- LeetCode 12 - Integer to Roman
- 个人记录-LeetCode 12. Integer to Roman
- 12-m-Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- LeetCode 12. Integer to Roman & 13. Roman to Integer
- [LeetCode] 12. Integer to Roman
- LeetCode 12 Integer to Roman
- FTPrep, 12 Integer to Roman
- LeetCode 12. Integer to Roman
- [Leetcode 44] 12 Integer To Roman
- leetcode 12 Integer to Roman
- LeetCode题解(12)--Integer to Roman