12. Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

1刷
题解:
数值计算的题目,需要了解罗马数字的规律。
Time Complexity - O(n), Space Complexity - O(n)

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

由于在submit时出现了time exceed,于是试试binary search

public class Solution {
    public String intToRoman(int num) {
        //Roman:   I = 1,  V = 5,   X = 10,   L = 50,   C = 100,  D = 500,  M = 1000 
        if(num<=0) return "";
        StringBuilder res = new StringBuilder();
        String[] symbol = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int [] value = {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1};
        while(num>0){
            int indice = binarySearch(num, value, 0, value.length);
            res.append(symbol[indice]);
            num -= value[indice];
        }
        return res.toString();
    }
    
    int binarySearch(int num, int[] value, int start, int end){
        int median = 0;
        while(start<=end){
            median = start + (end - start)/2;
            if(value[median] > num){
                start = median + 1;
            }
            else if(value[median] < num) end = median - 1;
            else return median;
        }
        
        median = value[median] > num? median+1:median;
        return median;
    }
}

你可能感兴趣的:(12. Integer to Roman)