标签:leetcode
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
题目解析:数字转罗马字符,关于罗马字符跟数字之间关系请参照上一篇罗马字符与数字关系
算法分析:这里没有使用哈希表,主要是遍历使用起来不够方便,而是采用了整型和字符数组,见AC代码
public String intToRoman(int num) { if (num <= 0) return null; int[] nums = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; String[] symbols = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; StringBuilder sb = new StringBuilder(); int i = 0; while (num > 0) { if (num / nums[i] == 0) { // 说明num量级不够 i++; continue; } num -= nums[i]; // 在字符串找到对应的字符 sb.append(symbols[i]); } return sb.toString(); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode
原文地址:http://blog.csdn.net/xsf50717/article/details/47322167