Source Link:
https://leetcode.com/problems/roman-to-integer/description/
Question:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
My Solution:
Note:
1. new an integer array to store all the numbers
int[] nums = new int[ s.length() ];
2. convert each "char" to "number"
for(int i=0; i<s.length(); i++){
if(s.charAt(i) == 'M'){
nums[i] = 1000;
}
...
}
3. to compute the sum
// note: from bigger one to smaller one -> sum = sum + nums
// note: if nums[j] == nums[j+1] -> sum = sum + nums (be careful)
// note: from smaller one to bigger one -> sum = sum - nums (important)
for(int j=0; j< s.length()-1 ; j++){
if(nums[j] >= nums[j+1]){
sum = sum + nums[j];
}
else{
sum = sum - nums[j];
}
}
4. note: the final one -> sum = sum + nums
sum = sum + nums[ s.length()-1 ];
5. return
return sum;
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