标签:style class blog code java http
一次过
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 }
Leetcode: Integer to Roman,布布扣,bubuko.com
标签:style class blog code java http
原文地址:http://www.cnblogs.com/EdwardLiu/p/3779785.html