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();
Subscribe to:
Post Comments (Atom)
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 ...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_distinct_slices/ Question: An integer M and a...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_triangles/ Question: A zero-indexed array A consi...
-
Source Link: https://codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/ Question: A non-empty zero-indexed array A...
No comments:
Post a Comment