【LeetCode】012.Integer to Roman
来源:互联网 发布:网络链路冗余技术 编辑:程序博客网 时间:2024/06/05 11:17
题目:
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 --- 8chars = new char[c - 5 + 1];Arrays.fill(chars, char1);chars[0] = char5;str.append(chars);} else if (c == 4) // 4str.append(char1).append(char5);else if(c > 0){ // 1 --- 3chars = new char[c];Arrays.fill(chars, char1);str.append(chars);}mode /= 10;}return str.toString();}}
0 0
- LeetCode 012. Integer to Roman
- 【LeetCode】012.Integer to Roman
- 【LeetCode】 012. Integer to Roman
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- LeetCode Integer to Roman & Roman to Integer
- leetcode - roman to integer & integer to roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- LeetCode Integer to Roman
- LeetCode: Integer to Roman
- LeetCode : Roman to Integer
- [Leetcode] Roman to Integer
- [Leetcode] Integer to Roman
- Leetcode: Integer to Roman
- uva 297
- Ehcache 整合Spring 使用页面、对象缓存
- C#中文转拼音
- javascript笔记:深入分析javascript里对象的创建(上)续篇
- 第十一周项目2 - 职员有薪水了
- 【LeetCode】012.Integer to Roman
- 浅谈凸优化问题中的Bregman迭代算法
- git忽略已经被提交的文件
- 关于网络编程的总结
- 本来我觉得半天可以解决的编译错误,现在看来一天都搞不定了
- a
- javascript笔记:深入分析javascript里对象的创建(中)
- svn中的状态简称
- 1.1顺序表基本操作的设计与实现