Created
July 8, 2013 07:52
-
-
Save luoxiaoxun/5946970 to your computer and use it in GitHub Desktop.
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
This file contains hidden or 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
| C++: | |
| class Solution { | |
| public: | |
| string intToRoman(int num) { | |
| // Start typing your C/C++ solution below | |
| // DO NOT write int main() function | |
| const static char *Roman="IVXLCDM"; | |
| string ret; | |
| for(int base=0;num;num /=10,base=base+2){ | |
| int cur=num%10; | |
| switch(cur){ | |
| case 1:case 2:case 3: | |
| ret =string(cur,Roman[base])+ret; | |
| break; | |
| case 4: | |
| ret =Roman[base+1]+ret; | |
| ret =Roman[base]+ret; | |
| break; | |
| case 5: | |
| ret =Roman[base+1]+ret; | |
| break; | |
| case 6:case 7:case 8: | |
| ret =string(cur-5,Roman[base])+ret; | |
| ret =Roman[base+1]+ret; | |
| break; | |
| case 9: | |
| ret =Roman[base+2]+ret; | |
| ret =Roman[base]+ret; | |
| break; | |
| default: | |
| break; | |
| } | |
| } | |
| return ret; | |
| } | |
| }; | |
| Java: | |
| public class Solution { | |
| public String intToRoman(int num) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| char[] Roman="IVXLCDM".toCharArray(); | |
| StringBuilder ret=new StringBuilder(); | |
| for(int base=0;num>0;num /=10,base=base+2){ | |
| int cur=num%10; | |
| switch(cur){ | |
| case 1:case 2:case 3: | |
| for(int i=0;i<cur;i++) ret.insert(0,Roman[base]); | |
| break; | |
| case 4: | |
| ret.insert(0,Roman[base+1]); | |
| ret.insert(0,Roman[base]); | |
| break; | |
| case 5: | |
| ret.insert(0,Roman[base+1]); | |
| break; | |
| case 6:case 7:case 8: | |
| for(int i=0;i<cur-5;i++) ret.insert(0,Roman[base]); | |
| ret.insert(0,Roman[base+1]); | |
| break; | |
| case 9: | |
| ret.insert(0,Roman[base+2]); | |
| ret.insert(0,Roman[base]); | |
| break; | |
| default: | |
| break; | |
| } | |
| } | |
| return ret.toString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment