题目描述:
学习记录:
好像之前做过,简单复制一下
class Solution {
public:
string intToRoman(int num)
{
string result="";
int temp=num/1000;
for(int i=0;i<temp;i++)
{
result+="M";
}
temp=(num%1000)/100;
if(temp==9)
{
result+="CM";
}
else if(temp<=8 && temp>=5)
{
result+="D";
temp%=5;
for(int i=0;i<temp;i++)
{
result+="C";
}
}
else if(temp==4)
{
result+="CD";
}
else
{
for(int i=0;i<temp;i++)
{
result+="C";
}
}
temp=((num%1000)%100)/10;
if(temp==9)
{
result+="XC";
}
else if(temp<=8 && temp>=5)
{
result+="L";
temp%=5;
for(int i=0;i<temp;i++)
{
result+="X";
}
}
else if(temp==4)
{
result+="XL";
}
else
{
for(int i=0;i<temp;i++)
{
result+="X";
}
}
temp=((num%1000)%100)%10;
if(temp==9)
{
result+="IX";
}
else if(temp<=8 && temp>=5)
{
result+="V";
temp%=5;
for(int i=0;i<temp;i++)
{
result+="I";
}
}
else if(temp==4)
{
result+="IV";
}
else
{
for(int i=0;i<temp;i++)
{
result+="I";
}
}
return result;
}
};
题解为什么这么短,康康:
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;
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/integer-to-roman/solution/zheng-shu-zhuan-luo-ma-shu-zi-by-leetcod-75rs/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
这里有几个知识点学习一下:
1.pair的用法:pair包含两个数值,与容器一样,pair也是一种模板类型。但是又与之前介绍的容器不同,在创建pair对象时,必须提供两个类型名,两个对应的类型名的类型不必相同。pair是将2个数据组合成一组数据的一种数据类型。如果要定义多个pair可以用数组或者 typedef vector< pair<string, int> > VP; VP vp; 这种形式。功能:将一对值合在一起,比如二维坐标(x,y),当然可以用结构体实现,但是使用pair有它的简洁之处。两个值分别通过 .first 和 .second 来访问。
2.auto的用法:auto是一个C/C++语言存储类型,仅在语句块内部使用,初始化可为任何表达式,其特点是当执行流程进入该语句块的时候初始化可为任何表达式。C语言中提供了存储说明符auto、register、extern、static说明的四种存储类别。四种存储类别说明符有两种存储期:自动存储期和静态存储期。其中auto和register对应自动存储期。具有自动存储期的变量在进入声明该变量的程序块时被建立,它在该程序块活动时存在,退出该程序块时撤销。在函数内部定义的变量成为局部变量。auto tnumber = 9;自动判断类型,auto outNumber : testNumber
3.运行0s;去掉const,运行变为4s;去掉&,运行变成8s。目前没有搞懂