来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-and-say
题目
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1
11
21
1211
111221
1 被读作 "one 1" ("一个一") , 即 11。
11 被读作 "two 1s" ("两个一"), 即 21。
21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
示例 1:
输入: 1
输出: "1"
示例 2:
输入: 4
输出: "1211"
方法1--10的时候会溢出
func countAndSay(_ n: Int) -> String {
var currentCount = 1
if n > 1 {
for i in 2...n {
currentCount = getNumCount(n: currentCount)
}
}
return String(currentCount)
}
func getNumCount(n: Int) -> Int {
var powNum = 0
var currentN = n
var result = 0
var currentNum = currentN % 10 //此时的最后一位
var currentNum_num = 0//几个此数
//如果是i=1,则
while currentN > 0 {
let newCurrnetNum = currentN % 10
if newCurrnetNum == currentNum {
currentNum_num += 1
currentN = currentN/10
}else {
result = (currentNum_num * 10 + currentNum) * Int(powf(10, Float(powNum))) + result
currentNum_num = 0
powNum += 2
currentNum = currentN % 10
}
}
if currentNum_num != 0 {
result = (currentNum_num * 10 + currentNum) * Int(pow(Double(10), Double(powNum))) + result
}
return result
}
前九个可以,10的时候,溢出。
方法2-字符串来遍历
func countAndSay(_ n: Int) -> String {
var currentCount = "1"
if n > 1 {
for i in 2...n {
currentCount = getNumCount(n: currentCount)
}
}
return String(currentCount)
}
func getNumCount(n: String) -> String {
var resultStr = ""
var resultNum = 0
var needAddStr = false
var currentNum_num = 0//几个此数
var currentStr = n.first!
//如果是i=1,则
for character in n {
if character == currentStr {
needAddStr = true
currentNum_num += 1
}else {
needAddStr = false
resultNum = currentNum_num * 10 + Int(String(currentStr))!
resultStr = resultStr + String(resultNum)
currentNum_num = 1
currentStr = character
}
}
resultNum = currentNum_num * 10 + Int(String(currentStr))!
resultStr = resultStr + String(resultNum)
return resultStr
}
网友评论