Leetcode 12 and Leetcode 13
5.14和5.15的每日一题 ,貌似没有什么可写的,可能就需要用StringBuilder来构建string
12. 整数转罗马数字
class Solution {
public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
for (int i = 0; i < values.length; i++) {
int val = values[i];
while (num >= val){
num -= val;
sb.append(getStr(val));
if (num == 0)
break;
}
}
return sb.toString();
}
private String getStr(int num){
switch (num){
case 1000:
return "M";
case 900:
return "CM";
case 500:
return "D";
case 400:
return "CD";
case 100:
return "C";
case 90:
return "XC";
case 50:
return "L";
case 40:
return "XL";
case 10:
return "X";
case 9:
return "IX";
case 5:
return "V";
case 4:
return "IV";
case 1:
return "I";
}
return null;
}
}
13. 罗马数字转整数
public int romanToInt(String s) {
int count = 0;
int size = s.length();
for (int i = 0; i < size; i++) {
if (i + 1 == size)
count += getVal(s.charAt(i));
else {
if (getVal(s.charAt(i + 1)) <= getVal(s.charAt(i)))
count += getVal(s.charAt(i));
else {
count += getVal(s.charAt(i + 1)) - getVal(s.charAt(i));
i++;
}
}
}
return count;
}
public int getVal(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;
default:
return 0;
}
}