Saturday, September 2, 2017

LeetCode - 12. Integer to Roman

Source Link:
https://leetcode.com/problems/integer-to-roman/description/

Question: 

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

My Solution:
Note:
1. store all the possible "numbers" and "strings"
int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
2. Using "StringBuilder" (important)
StringBuilder string_builder = new StringBuilder();
3. for each possible nums (from big one to small one)
for(int i=0; i < nums.length; i++){
while( num >= nums[i]){
num = num - nums[i];
string_builder.append(roman[i]);  
}
4. Using "toString()"
return string_builder.toString(); 

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...