一、题目原型:
可参考 13. 罗马数字转整数
二、题目意思剖析:
其实就是和 13. 罗马数字转整数反着来
输入: 3
输出: "III"
输入: 4
输出: "IV"
输入: 9
输出: "IX"
输入: 58
输出: "LVIII"
解释: C = 100, L = 50, XXX = 30, III = 3.
输入: 1994
输出: "MCMXCIV"
解释: M = 1000, CM = 900, XC = 90, IV = 4.
三、解题思路:
func intToRoman(_ num: Int) -> String {
if num<1 || num>3999 {
return ""
}
var tempNum = num
var arr: [Int] = []
while tempNum != 0 {
arr.append(tempNum % 10)
tempNum = tempNum / 10
}
var numArr: [Int] = Array.init(repeating: 0, count: arr.count)
for i in 0..<arr.count {
let haha: Int = Int.init(pow(10.0, Double(i)))
numArr[arr.count - 1 - i] = haha * arr[i]
}
var resultStr: String = ""
for i in 0..<numArr.count {
var num: Int = numArr[i]
if num == 900 {
resultStr += "CM"
}else if num == 400 {
resultStr += "CD"
}else if num == 90 {
resultStr += "XC"
}else if num == 40 {
resultStr += "XL"
}else if num == 9 {
resultStr += "IX"
}else if num == 4 {
resultStr += "IV"
}else if num % 1000 == 0 {
for _ in 0..<num / 1000 {
resultStr += "M"
}
}else if num > 500 && num < 1000{
num = num - 500
resultStr += "D"
for _ in 0..<num / 100 {
resultStr += "C"
}
}else if num == 500 {
resultStr += "D"
}else if num % 100 == 0 && num < 500{
for _ in 0..<num / 100 {
resultStr += "C"
}
}else if num > 50 && num < 100{
num = num - 50
resultStr += "L"
for _ in 0..<num / 10 {
resultStr += "X"
}
}else if num == 50 {
resultStr += "L"
}else if num % 10 == 0 && num < 50 {
for _ in 0..<num / 10 {
resultStr += "X"
}
}else if num < 10 && num > 5 {
num = num - 5
resultStr += "V"
for _ in 0..<num {
resultStr += "I"
}
}else if num == 5 {
resultStr += "V"
}else if num <= 3 {
for _ in 0..<num / 1 {
resultStr += "I"
}
}
}
return resultStr
}
// 优化方案
func intToRoman(_ num: Int) -> String {
if num<1 || num>3999 {
return ""
}
var lala = num
var resultStr: String = ""
let numList = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
let romanList = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX",
"V", "IV", "I"]
for i in 0..<numList.count {
if lala < numList[i] {
continue
}
while lala >= numList[i] {
lala = lala - numList[i]
resultStr += romanList[i]
}
}
return resultStr
}
四、小结
第一种方法看起来是不是特麻烦,我写起来的时候也是,得想清楚。。。
之后优化的方案清晰多了。
总提交数 提交结果
有其他好的方法请极速留言,非常乐意一起探讨。😄
网友评论