F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

[Leetcode] Integer to Roman

第三次刷这个题了,这次一次A过!总结起来是利用了小于4000的数字的罗马数字表示上的相对独立性,我们可以只针对正数表示的个位、十位、百位、千位来分别设计计算的策略。

0: return “”

1-3:return相应数字个当前符号

4:返回当前符号+高一级的符号

5:返回高一级符号

6-8:返回高一级符号+相应数量的当前符号

9:当前符号+高两级的符号

上代码:

 1 import java.util.*;
 2 
 3 public class Solution {
 4     private String getUnit(int digit, String currentNotation, String largerNotation,String largerlargerNotation){
 5         String res = "";
 6         if(digit==0) return "";
 7         if(digit<=3){
 8             for(int i=0;i<digit;i++) res+=currentNotation;
 9         }else if(digit==4){
10             res = currentNotation + largerNotation;
11         }else if(digit<=8){
12             res = largerNotation;
13             digit = digit - 5;
14             for(int i=0;i<digit;i++) res = res + currentNotation;
15         }else{
16             res = currentNotation + largerlargerNotation;
17         }
18         return res;
19     }
20     public String intToRoman(int num) {
21         String res = "";
22         int gewei = num %10;
23         int shiwei = (num/10)%10;
24         int baiwei = (num/10/10)%10;
25         int qianwei = (num/10/10/10)%10;
26         String qianString = getUnit(qianwei,"M","","");
27         res = res + qianString;
28         String baiString = getUnit(baiwei,"C","D","M");
29         res = res + baiString;
30         String shiString = getUnit(shiwei,"X","L","C");
31         res = res + shiString;
32         String geString = getUnit(gewei,"I","V","X");
33         res = res + geString;
34         return res;
35     }
36 }

 

posted on 2015-08-23 18:51  F_G  阅读(142)  评论(0编辑  收藏  举报