Last active
December 11, 2015 18:58
-
-
Save guolinaileen/4645401 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string intToRoman(int num) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
string result=""; | |
if(num>=1000) result+=string(num/1000, 'M'); | |
num=num%1000; result+=stringHelper(num/100, "C", "D", "M"); | |
num=num%100; result+=stringHelper(num/10, "X", "L", "C"); | |
num=num%10; result+=stringHelper(num, "I", "V", "X"); | |
return result; | |
} | |
string stringHelper(int num, string one, string five, string ten) | |
{ | |
string result=""; | |
switch(num) | |
{ | |
case 1: case 2: case 3: | |
return string(num, one[0]); | |
case 4: | |
return one+five; | |
case 5: | |
return five; | |
case 6: case 7: case 8: | |
return five+string(num-5, one[0]); | |
case 9: | |
return one+ten; | |
} | |
return result; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public String intToRoman(int num) { | |
StringBuffer sb=new StringBuffer(); | |
while(num>=900) | |
{ | |
if(num>=900 && num<1000) | |
{ | |
sb.append("C"); | |
num+=100; | |
} | |
while(num>=1000) | |
{ | |
sb.append("M"); | |
num-=1000; | |
} | |
} | |
while(num<900&&num>=90) | |
{ | |
if(num>=500) | |
{ | |
num-=500; | |
sb.append("D"); | |
}else if(num>=400) | |
{ | |
num+=100; | |
sb.append("C"); | |
continue; | |
} | |
if(num>=90&& num<100) | |
{ | |
num+=10; | |
sb.append("X"); | |
} | |
while(num>=100) | |
{ | |
num-=100; | |
sb.append("C"); | |
} | |
} | |
while(num>=9 && num<90) | |
{ | |
if(num>=50) | |
{ | |
num-=50; | |
sb.append("L"); | |
}else if(num>=40) | |
{ | |
num+=10; | |
sb.append("X"); | |
continue; | |
} | |
if(num==9) | |
{ | |
num+=1; | |
sb.append("I"); | |
} | |
while(num>=10) | |
{ | |
num-=10; | |
sb.append("X"); | |
} | |
} | |
while(num>=1 && num<9) | |
{ | |
if(num==4) | |
{ | |
num+=1; | |
sb.append("I"); | |
} | |
if(num>=5) | |
{ | |
num-=5; | |
sb.append("V"); | |
} | |
while(num>=1) | |
{ | |
num-=1; | |
sb.append("I"); | |
} | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment