您的位置:首页 > 其它

leetcode-12 Integer to Roman

2016-11-01 23:01 239 查看
Question:

Given an integer, convert it to a roman numeral.

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

阿拉伯数字与罗马数字的对应关系为:

        String roms[] = {"I", "V", "X", "L", "C", "D", "M"};

        int aras[] = {1, 5, 10, 50, 100, 500, 1000};

其中,特殊的是:

当i % 2 == 0时(偶数),aras[i] - aras[i-2] = roms[i-2] + roms[i];

当i % 2 != 0 时(奇数),aras[i] - aras[i-1] = roms[i-1] + roms[i];

java代码如下:

public class Solution {

    public String intToRoman(int num) {

        String roms[] = {"I", "V", "X", "L", "C", "D", "M"};

        int aras[] = {1, 5, 10, 50, 100, 500, 1000};

        int temp = num;

        String res = "";

        for(int i = 6; i >= 0; i --){

            int p = temp / aras[i];

            if(p >= 1){

                for(int j = 0; j < p; j ++){

                    res += roms[i];

                }

                temp = temp % aras[i];

                i ++;

            }

            else{

                if(i > 0 && i % 2 == 0){

                    if(temp / (aras[i] - aras[i-2]) == 1){

                        res = res + roms[i-2] + roms[i];

                        temp = temp - (aras[i] - aras[i-2]);

                    }

                }

                else if(i % 2 != 0){

                    if(temp / (aras[i] - aras[i-1]) == 1){

                        res = res + roms[i-1] + roms[i];

                        temp = temp - (aras[i] - aras[i-1]);

                    }

                }

            }

        }

        return res;

        

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: