力扣 12 整数转罗马数字 C++

题目

知识点

C++标准库utility

题目解释

题解

逐位编码------低位到高位

answer = substr + answer;//不可以交换位置!!!

复制代码
class Solution {
public:
    string intToRoman(int num) {
        string answer = "";//存放最终结果
        int mo;//mo存放当前要处理的数字
        int d = 0;//d表示当前正处理第d位(个位 十位 百位)
        char ch_10[] = { 'I','X','C','M' };//1个位  10十位  100  1000
        char ch_5[] = { 'V','L','D' };//5个位  50十位  500

        while(num > 0){
            string substr = "";//临时存放当前位的处理结果
            mo = num % 10;
            if(mo == 4){//4 IV
                substr = substr + ch_10[d] + ch_5[d];//4 IV 1在前,5在后
            }else if(mo == 9){//9 IX
                substr = substr + ch_10[d] + ch_10[d + 1];//9 IX 1在前,10在后
            }else if(mo >= 5 && mo <= 8){
                substr.insert(substr.begin(),ch_5[d]);//将字符ch_5[d]插入到字符串substr的开头
                for(int i=0 ; i<(mo-5) ;i++){
                    substr = substr + ch_10[d];//在substr后面加上表示1的字符------I
                }
            }else{
                for(int i=0;i<mo;i++){
                    substr = substr + ch_10[d];
                }
            }
            answer = substr + answer;//不可以交换位置!!!
            d++;
            num /= 10;
        }//while

        return answer;
    }
};

大数查表法------高位到低位

复制代码
const pair<int, string> valueSymbols[] = {
	{1000,"M"},
	{900,"CM"},
	{500,"D"},
	{400,"CD"},
	{100,"C"},
	{90,"XC"},
	{50,"L"},
	{40,"XL"},
	{10,"X"},
	{9,"IX"},
	{5,"V"},
	{4,"IV"},
	{1,"I"},
};

class Solution {
public:
	string intToRoman(int num) {
		string roman;
		for (const auto& [value, symbol] : valueSymbols) {
			while (num >= value) {
				num -= value;
				roman += symbol;
			}
			if (num == 0) {
				break;
			}
		}
		return roman;
	}
};
相关推荐
在爪洼山玩泥巴27 分钟前
fastjson2 JSONPath 取不存在路径,为什么会抛 “not support”?
java·开发语言·jsonpath·fastjson
星落梦生10 小时前
SpringAOP基础笔记(7)
java·开发语言
我不会插花弄玉11 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
曹牧12 小时前
Java:“刷新雪崩”
java·开发语言
郝学胜-神的一滴12 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus13 小时前
C++ explicit 关键字工程实践
开发语言·c++
郝学胜-神的一滴15 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
feixing_fx15 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
LK_0715 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk55515 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel