首页 > 其他 > 详细

【LeetCode】Integer to Roman

时间:2014-05-12 09:35:19      阅读:452      评论:0      收藏:0      [点我收藏+]

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

bubuko.com,布布扣
public class Solution {
    public String intToRoman(int num) {
        StringBuilder sb = new StringBuilder();
        if(num==0)
            return sb.toString();
        while(num!=0){
            if(num>=1000){
                int temp = num/1000;
                for(int i=0;i<temp;i++)
                    sb.append("M");
                num = num%1000;
                continue;
            }
            if(num>=500){
                if(num/900==1){
                    sb.append("CM");
                    num=num%900;
                    continue;
                }
                num = num%500;
                sb.append("D");
                
            }
            if(num>=100){
                if(num/400==1){
                    sb.append("CD");
                    num=num%400;
                    continue;
                }
                int temp = num/100;
                for(int i=0;i<temp;i++)
                    sb.append("C");
                num=num%100;
                continue;
            }
            if(num>=50){
                if(num/90==1){
                    sb.append("XC");
                    num=num%90;
                    continue;
                }
                num=num%50;
                sb.append("L");
                continue;
            }
            if(num>=10){
                if(num/40==1){
                    sb.append("XL");
                    num=num%40;
                    continue;
                }
                int temp = num/10;
                for(int i=0;i<temp;i++)
                    sb.append("X");
                num=num%10;
                continue;
            }
            if(num>=5){
                if(num/9==1){
                    sb.append("IX");
                    num=num%9;
                    continue;
                }
                num=num%5;
                sb.append("V");
                continue;
            }
            if(num>=1){
                if(num/4==1){
                    sb.append("IV");
                    num=num%4;
                    continue;
                }
                int temp = num;
                for(int i=0;i<temp;i++)
                    sb.append("I");
                num=0;
                continue;
            }
        }
        return sb.toString();
        
    }
}
bubuko.com,布布扣

 

【LeetCode】Integer to Roman,布布扣,bubuko.com

【LeetCode】Integer to Roman

原文:http://www.cnblogs.com/yixianyixian/p/3720649.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!