leetcode12 整数转罗马数字

tags:字符串  模拟题

leetcode12 整数转罗马数字_第1张图片

 leetcode12 整数转罗马数字_第2张图片

 1994 先是和1000比,比1000大,于是添加一个M,然后1994变成994

再和1000比,比1000小,于是去和900比,比900大,于是添加CM,994变成94......

1:"I"

4:"IV"

5:"V"

9:"IX"

10:"X"

40:"XL"

50:"L"

90:"XC"

100:"C"

400:"CD"

500:"D"

900:"CM"

1000:"M"

 

class Solution {
    public String intToRoman(int num) {

       int[]  nums={1,4,5,9,10,40,50,90,100,400,500,900,1000};
       String[] codes={"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
 
       StringBuilder result=new StringBuilder();
       for(int i=nums.length-1;i>=0;i--){
         while(num>=nums[i]){
             result.append(codes[i]); 
             num=num-nums[i];
             if(num==0){
                 return result.toString();
             }
         }
       }
       return   result.toString();
    }
}

你可能感兴趣的:(leetcode,leetcode)