Leetcode 12. Integer to Roman

GoodJobJasper發表於2020-12-30

在這裡插入圖片描述
方法1: 這題我們可以列舉出所有羅馬數字的組合,然後遍歷num。時間複雜1,因為最多output長度為15,是一個定值。空間複雜1.

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

總結:

相關文章