[leetcode] 12. 整数转罗马数字

12. 整数转罗马数字

字符串处理,题超级简单,读懂题直接开干就行。
基本思路就是从大往小一点一点的来表示,具体看代码把:

class Solution {
public:
    string intToRoman(int num) {
        string ans = "";

        int m = 0;
        m = num / 1000;
        for (int i = 0; i < m; i++) {
            ans += 'M';
        }
        num %= 1000;

        if (num >= 900) {
            ans += "CM";
            num -= 900;
        }
        if (num >= 500) {
            ans += "D";
            num -= 500;
        }
        if (num >= 400) {
            ans += "CD";
            num -= 400;
        }
        if (num >= 100) {
            int c = 0;
            c = num / 100;
            num %= 100;
            for (int i = 0; i < c; i++) {
                ans += 'C';
            }
        }
        if (num >= 90) {
            ans += "XC";
            num -= 90;
        }
        if (num >= 50) {
            ans += "L";
            num -= 50;
        }
        if (num >= 40) {
            ans += "XL";
            num -= 40;
        }
        if (num >= 10) {
            int x = 0;
            x = num / 10;
            num %= 10;
            for (int i = 0; i < x; i++) {
                ans += 'X';
            }
        }

        if (num >= 9) {
            ans += "IX";
            num -= 9;
        }
        if (num >= 5) {
            ans += "V";
            num -= 5;
        }
        if (num >= 4) {
            ans += "IV";
            num -= 4;
        }
        if (num >= 1) {
            int i = 0;
            i = num;
            for (int k = 0; k < i; k++) {
                ans += 'I';
            }
        }

        return ans;
    }
};
posted @ 2018-06-26 22:50  ACBingo  阅读(196)  评论(0编辑  收藏  举报