首页 > 代码库 > Leetcode: Integer to Roman
Leetcode: Integer to Roman
一次过
1 public class Solution { 2 public String intToRoman(int num) { 3 StringBuffer res = new StringBuffer(); 4 if (num > 3999 || num < 1) return res.toString(); 5 int copy = num; 6 int thousand = copy / 1000; //# of thousand 7 copy = copy - thousand * 1000; 8 int hundred = copy / 100; //# of hundred 9 copy = copy - hundred * 100; 10 int ten = copy / 10; //# of ten 11 copy = copy - ten * 10; 12 int one = copy / 1; //# of one 13 14 if (thousand != 0) { //thousand 15 switch (thousand) { 16 case 1: res.append("M"); break; 17 case 2: res.append("MM"); break; 18 case 3: res.append("MMM"); break; 19 } 20 } 21 22 if (hundred != 0) { //thousand 23 switch (hundred) { 24 case 1: res.append("C"); break; 25 case 2: res.append("CC"); break; 26 case 3: res.append("CCC"); break; 27 case 4: res.append("CD"); break; 28 case 5: res.append("D"); break; 29 case 6: res.append("DC"); break; 30 case 7: res.append("DCC"); break; 31 case 8: res.append("DCCC"); break; 32 case 9: res.append("CM"); break; 33 } 34 } 35 36 if (ten != 0) { //thousand 37 switch (ten) { 38 case 1: res.append("X"); break; 39 case 2: res.append("XX"); break; 40 case 3: res.append("XXX"); break; 41 case 4: res.append("XL"); break; 42 case 5: res.append("L"); break; 43 case 6: res.append("LX"); break; 44 case 7: res.append("LXX"); break; 45 case 8: res.append("LXXX"); break; 46 case 9: res.append("XC"); break; 47 } 48 } 49 50 if (one != 0) { //thousand 51 switch (one) { 52 case 1: res.append("I"); break; 53 case 2: res.append("II"); break; 54 case 3: res.append("III"); break; 55 case 4: res.append("IV"); break; 56 case 5: res.append("V"); break; 57 case 6: res.append("VI"); break; 58 case 7: res.append("VII"); break; 59 case 8: res.append("VIII"); break; 60 case 9: res.append("IX"); break; 61 } 62 } 63 return res.toString(); 64 } 65 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。