Input is guaranteed to be within the range from 1 to 3999.
- public class Solution {
- public String intToRoman(int num) {
- int[] number = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
- String[] str = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
- StringBuilder sb=new StringBuilder();
- for(int i = 0;i<number.length;i++){
- while(number[i]<=num){
- num-=number[i];
- sb.append(str[i]);
- }
- }
- return sb.toString();
- }
- }
public class Solution { public String intToRoman(int num) { int[] number = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; String[] str = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; StringBuilder sb=new StringBuilder(); for(int i = 0;i
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
- public class Solution {
- public int romanToInt(String s) {
- int[] number = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
- String[] str = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX",
- "V", "IV", "I" };
- int it = 0, res = 0;
- for (int i = 0; i < str.length; i++) {
- for (int j = 2; j >= 1; j--) {
- if(it==s.length()-1) j=1;
- while (s.substring(it, it + j).equals(str[i])) {
- it+=j;
- if(it==s.length()-1) j=1;
- res+=number[i];
- if(it>=s.length()){
- return res;
- }
- }
- }
- }
- return res;
- }
- }