leetcode12 convert integer to Roman numeral

tags: string simulation questions

 

 1994 is first compared with 1000 and is larger than 1000, so an M is added, and then 1994 becomes 994

Then compare it with 1000, it is smaller than 1000, so compare it with 900, it is larger than 900, so add CM, 994 becomes 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();
    }
}

おすすめ

転載: blog.csdn.net/weixin_47414034/article/details/131853384