Sunday, February 23, 2014

[LEETCODE] Integer to Roman

[LEETCODE] Integer to Roman

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

思路:
Following is how integer is represented as Roman. 
















当数字为1 和 5 的10 或10次方倍数时,罗马数字改变,小于1-3时为1的重复,4为在5左边添加1, 6-8 为在5的右边添加1,9为在新1的左边加旧1.

注意:
1. char name[number] = {" ", " ", " "} char数组的赋值
2. string result的用法:
    1) result.append(个数,char); 个数一定要有,最小为1;
    2) result.push_back(char/string); 一次只push一个进去.

代码:
string intToRoman(int num) {
string result;
char roman[7]= {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
int newnum = num;
int count = 0;
while(newnum != 0){
newnum /= 10;
count ++;
}
while(count != 0){
int newcount = 1;
int divide=1;
while(newcount != count){
divide *= 10;
newcount ++;
}
int cur = num/divide;
num = num%divide;
int romind = (count-1)*2;
if(cur < 4){ result.append(cur, roman[romind]);}
else if(cur == 4) {
result.append(1, roman[romind]);
result.append(1, roman[romind+1]);
}
else if(cur == 5){
result.append(1, roman[romind+1]);
}
else if(cur < 9){
result.append(1, roman[romind+1]);
result.append(cur - 5, roman[romind]);
}
else if(cur == 9){
result.append(1, roman[romind]);
result.append(1, roman[romind+2]);
}
count --;
}
return result;
}

No comments:

Post a Comment