【LeetCode】012.Integer to Roman
2015-05-20 12:25
253 查看
题目:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解答:
从千位到个位,根据位数不同选择不同的字母,char1,char5,char10分别代表该位表示1,5和10的字母。
c为当前位数字(0---9),模式为:
c -- 9 char1 + char10
c :5 ---8 char5 + char1[c-5]
c:4 char1+char5
c:1--3 char1[c]
代码:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解答:
从千位到个位,根据位数不同选择不同的字母,char1,char5,char10分别代表该位表示1,5和10的字母。
c为当前位数字(0---9),模式为:
c -- 9 char1 + char10
c :5 ---8 char5 + char1[c-5]
c:4 char1+char5
c:1--3 char1[c]
代码:
public class Solution { public String intToRoman(int num) { StringBuilder str = new StringBuilder(); char[] chars; char char1 = 0, char5=0,char10=0; int mode = 1000; while (mode > 0) { int c = num / mode; num %= mode; switch (mode) { case 1000: char1 = 'M'; if(c > 3) return "error"; break; case 100: char1 = 'C'; char5 = 'D'; char10 = 'M'; break; case 10: char1 = 'X'; char5 = 'L'; char10 = 'C'; break; case 1: char1 = 'I'; char5 = 'V'; char10 = 'X'; break; default: break; } if (c == 9) str.append(char1).append(char10); else if (c >= 5) { // 5 --- 8 chars = new char[c - 5 + 1]; Arrays.fill(chars, char1); chars[0] = char5; str.append(chars); } else if (c == 4) // 4 str.append(char1).append(char5); else if(c > 0){ // 1 --- 3 chars = new char[c]; Arrays.fill(chars, char1); str.append(chars); } mode /= 10; } return str.toString(); } }
相关文章推荐
- [leetcode刷题系列]Length of Last Word
- LeetCode(101)Symmetric Tree
- leetcode第一刷_4Sum
- 【leetcode刷题笔记】3Sum
- [leetcode] Sort List
- LeetCode Fraction to Recurring Decimal
- leetcode:Sum Root to Leaf Numbers
- leetcode 日经贴,Cpp code -Partition List
- Leetcode[118]-Pascal's Triangle
- 【leetcode】Valid Palindrome
- [LeetCode] Longest Substring with At Most Two Distinct Characters
- LeetCode--Single Number III
- Leetcode: Inorder Successor in BST
- 《leetCode》:Single Number III
- LeetCode 22. Generate Parentheses
- LeetCode:Interleaving String
- LeetCode: Count Primes(计算n以内素数个数:高效算法)
- LeetCode 127. Word Ladder
- leetcode_[python/C++]_91_Decode Ways_动态规划
- 个人记录-LeetCode 77. Combinations