【LeetCode解答六】Integer to Roman问题Java解答

来源:互联网 发布:知乎英国梨和小苍兰 编辑:程序博客网 时间:2024/05/16 19:50

Given an integer, convert it to a roman numeral.

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

以上是题目要求
想做这道题必须要明白罗马数字是怎么写的

阿拉伯数字 罗马数字 1 I 4 IV 5 V 9 IX 10 X 40 XL 50 L 90 XC 100 C 400 CD 500 D 900 CM 1000 M

这样就是1-1000的表示方式,题目要求最多输入3999,所以这就够用了,可以写代码了

package Q12IntegerToRoman;import java.util.Scanner;/** * @author 单继重 * @since 2017/11/2 18:45 */public class Solution {    public static String intToRoman(int num) {        String str = "";        String[] strings = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};        int[] values = {1,4,5,9,10,40,50,90,100,400,500,900,1000};        for (int i = 12 ; num !=0 ; i --) {            while (num >= values[i]) {                num -= values[i];                str += strings[i];            }        }        return str;    }    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        int num = scanner.nextInt();        System.out.println(intToRoman(num));    }}
原创粉丝点击