Integer to Roman
2016-02-25 13:32
239 查看
首先是我自己看完网上的罗马数规则写的又臭又长的代码!(捂脸!!)
下面的是网上流传比较简单的:
class Solution { public: string intToRoman(int num) { string s=""; int a[4]={0},i=3; while(num!=0) { a[i]=num%10; num=num/10; i--; } while(a[0]!=0) { s=s+'M'; a[0]--; } if(a[1]!=0) { if(a[1]==9) s=s+'C'+'M'; else if(a[1]>=5) { s=s+'D'; a[1]=a[1]-5; while(a[1]!=0) { s=s+'C'; a[1]--; } } else{ if(a[1]==4) s=s+'C'+'D'; else{ while(a[1]!=0) { s=s+'C'; a[1]--; } } } } if(a[2]!=0) { if(a[2]==9) s=s+'X'+'C'; else if(a[2]>=5) { s=s+'L'; a[2]=a[2]-5; while(a[2]!=0) { s=s+'X'; a[2]--; } } else{ if(a[2]==4) s=s+'X'+'L'; else{ while(a[2]!=0) { s=s+'X'; a[2]--; } } } } if(a[3]!=0) { if(a[3]==9) s=s+'I'+'X'; else if(a[3]>=5) { s=s+'V'; a[3]=a[3]-5; while(a[3]!=0) { s=s+'I'; a[3]--; } } else{ if(a[3]==4) s=s+'I'+'V'; else{ while(a[3]!=0) { s=s+'I'; a[3]--; } } } } return s; } };
下面的是网上流传比较简单的:
public static String intToRoman(int num) { String M[] = {"", "M", "MM", "MMM"}; String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10]; }
相关文章推荐
- 更改Tomcat配置,解决中文乱码问题
- Log4j源码解析--框架流程+核心解析
- Log4j源码解析--框架流程+核心解析
- String,StringBuffer与StringBuilder的区别??
- Android Studio新建工程Gradle编译报错(com.android.support:appcompat-v7:16.+)
- View RDD contents in Python Spark
- QT中QSignalMapper类信号转发器的使用和说明
- md5和fsha1笔记
- SQL 判断年份是否为润年
- HDU2009求数列的和(两种思想)
- JavaSE基础
- SpringMVC+redis整合
- 经典递归——斐波那契数列,汉诺塔
- vi 详解
- eclipse提示An SWT error has occurred 怎么处理?
- python 列表转为字典的两个小方法
- Avalon属性ms-text的坑
- XML Schema choice 元素
- HDOJ Train Problem I
- zstu 2552 马棚问题