Leetcode Integer to Roman
2016-07-19 04:56
309 查看
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Difficulty: Medium
public class Solution {
public String intToRoman(int num) {
String ans = "";
char[] c = new char[7];
c[0] = 'I';
c[1] = 'V';
c[2] = 'X';
c[3] = 'L';
c[4] = 'C';
c[5] = 'D';
c[6] = 'M';
for(int i = 0; i < 4; i++){
int temp = num%10;
if(temp <= 3 && temp >=1){
for(int j = 0; j < temp; j++){
ans = ans + c[i*2];
}
}
else if(temp == 4){
ans = ans + c[i*2 + 1];
ans = ans + c[i*2];
}
else if(temp >= 5 && temp <= 8){
for(int j = temp; j >= 6; j--){
ans = ans + c[i*2];
}
ans = ans + c[i*2 + 1];
}
else if(temp == 9){
ans = ans + c[i*2 + 2];
ans = ans + c[i*2];
}
num /= 10;
}
return (new StringBuilder(ans)).reverse().toString();
}
}
Input is guaranteed to be within the range from 1 to 3999.
Difficulty: Medium
public class Solution {
public String intToRoman(int num) {
String ans = "";
char[] c = new char[7];
c[0] = 'I';
c[1] = 'V';
c[2] = 'X';
c[3] = 'L';
c[4] = 'C';
c[5] = 'D';
c[6] = 'M';
for(int i = 0; i < 4; i++){
int temp = num%10;
if(temp <= 3 && temp >=1){
for(int j = 0; j < temp; j++){
ans = ans + c[i*2];
}
}
else if(temp == 4){
ans = ans + c[i*2 + 1];
ans = ans + c[i*2];
}
else if(temp >= 5 && temp <= 8){
for(int j = temp; j >= 6; j--){
ans = ans + c[i*2];
}
ans = ans + c[i*2 + 1];
}
else if(temp == 9){
ans = ans + c[i*2 + 2];
ans = ans + c[i*2];
}
num /= 10;
}
return (new StringBuilder(ans)).reverse().toString();
}
}
相关文章推荐
- Leetcode Valid Anagram
- Leetcode Single Number II
- 大公司还是小公司(非常全面和有道理,居然还是原创)
- Leetcode Pascal's Triangle
- Leetcode Balanced Binary Tree
- Leetcode Divide Two Integers
- Leetcode Sqrt(x)
- Leetcode Number of Digit One
- Leetcode Largest Number
- Leetcode Word Break II
- [leetcode] 118. Pascal's Triangle
- php判断是否为今天
- Codeforces Round #327 (Div. 2)
- 决策树算法(四)——选取最佳特征划分数据集
- 一键安装LAMP或LNMP
- [leetcode] 110. Balanced Binary Tree
- Leetcode 299. Bulls and Cows (Python)
- redhat7.2用户及用户组权限管理操作实例
- zabbix redis_low_level_discovery
- OSChina 周二乱弹 ——风流不需编码强,红袖无言意最长