Saturday, September 2, 2017

LeetCode - 13. Roman to Integer

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;

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 ...