java 解决Leetcode Integer and Roman 问题
Integer to Roman
查看题目点击这里
题目简介:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
代码实现如下:
/**
* Given an integer, convert it to a roman numeral.
* <p>
* Input is guaranteed to be within the range from 1 to 3999.
*/
public class IntegertoRoman {
public String intToRoman(int num) {
String[][] source = {
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "M", "MM", "MMM"}};
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(source[3][num / 1000]);
stringBuilder.append(source[2][num % 1000 / 100]);
stringBuilder.append(source[1][num % 1000 % 100 / 10]);
stringBuilder.append(source[0][num % 1000 % 100 % 10]);
return stringBuilder.toString();
}
}
Roman to Integer
题目地址:
https://leetcode.com/problems/roman-to-integer/
题目就是将罗马数字转化为阿拉伯数字
解法一代码如下:
public int romanToInt(String s) {
int tempInt = -1, result = 0;
String[][] source = {
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "M", "MM", "MMM"}};
tempInt = matchInt(s, 3, source);
s = s.substring(source[3][tempInt].length());
result = tempInt * 1000;
tempInt = matchInt(s, 2, source);
s = s.substring(source[2][tempInt].length());
result = result + tempInt * 100;
tempInt = matchInt(s, 1, source);
s = s.substring(source[1][tempInt].length());
result = result + tempInt * 10;
tempInt = matchInt(s, 0, source);
result = result + tempInt * 1;
return result;
}
private int matchInt(String s, int xRow, String[][] source) {
int temp = 0;
for (int i = source[xRow].length - 1; i >= 0; --i) {
if (source[xRow][i].length() != 0 && s.contains(source[xRow][i]) && s.substring(0, source[xRow][i].length()).equals(source[xRow][i])) {
temp = i;
break;
}
}
return temp;
}
解法二:该解法是查看了网上大神的思路。
public int romanToInt(String s) {
int result = 0,temp = 0;
for (int i = 0; i < s.length(); ++i) {
if(temp < toNumber(s.charAt(i))){
result = result + toNumber(s.charAt(i))-2*temp;
}else{
result = result + toNumber(s.charAt(i));
}
temp = toNumber(s.charAt(i));
}
return result;
}
private int toNumber(char ch) {
switch (ch) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
}
return 0;
}