前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 12. Integer to Roman题目分析代码

LeetCode 12. Integer to Roman题目分析代码

作者头像
desperate633
发布2018-08-22 15:49:14
2460
发布2018-08-22 15:49:14
举报
文章被收录于专栏:desperate633desperate633

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

题目

给定一个整数,将其转换成罗马数字。

返回的结果要求在1-3999的范围内。

说明什么是 罗马数字? https://en.wikipedia.org/wiki/Roman_numerals https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97 http://baike.baidu.com/view/42061.htm

样例4 -> IV

12 -> XII

21 -> XXI

99 -> XCIX

更多案例,请戳 http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm

分析

循环判断即可

代码

代码语言:javascript
复制
public class Solution {
    /**
     * @param n The integer
     * @return Roman representation
     */
    public String intToRoman(int num) {
        if(num <= 0)
            return "";
        
        String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        
        int digit = 0;
        StringBuilder sb = new StringBuilder();
        while(num > 0) {
            int times = num/nums[digit];
            num = num-times*nums[digit];
            
            for(;times>0;times--) {
                sb.append(symbols[digit]);
            }
            digit++;
        }
        return sb.toString();
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.03.26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档