-
Notifications
You must be signed in to change notification settings - Fork 41
/
38.swift
82 lines (66 loc) · 2.18 KB
/
38.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//
// CountAndSay.swift
// CountAndSay
//
// Created by Lex Tang on 5/5/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
/*
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
*/
import Foundation
import XCTest
func countAndSay(_ n: Int) -> String {
if n == 0 {
return ""
}
if n == 1 {
return "1"
}
var s = "1"
var i = 1
while i < n {
var cnt = 0
var last = s[0]
var newS = ""
for j in 0...s.count {
if s[j] == last {
cnt += 1
} else {
newS.append(Character("\(cnt)"))
newS.append(last!)
last = s[j]
cnt = 1
}
}
s = newS
i += 1
}
return s
}
class CountAndSayTest: XCTestCase {
func testCountAndSay() {
XCTAssertEqual(countAndSay(0), "", "")
XCTAssertEqual(countAndSay(1), "1", "")
XCTAssertEqual(countAndSay(2), "11", "")
XCTAssertEqual(countAndSay(3), "21", "")
XCTAssertEqual(countAndSay(4), "1211", "")
XCTAssertEqual(countAndSay(5), "111221", "")
XCTAssertEqual(countAndSay(6), "312211", "")
XCTAssertEqual(countAndSay(7), "13112221", "")
XCTAssertEqual(countAndSay(8), "1113213211", "")
XCTAssertEqual(countAndSay(9), "31131211131221", "")
XCTAssertEqual(countAndSay(10), "13211311123113112211", "")
XCTAssertEqual(countAndSay(11), "11131221133112132113212221", "")
XCTAssertEqual(countAndSay(12), "3113112221232112111312211312113211", "")
XCTAssertEqual(countAndSay(13), "1321132132111213122112311311222113111221131221", "")
XCTAssertEqual(countAndSay(14), "11131221131211131231121113112221121321132132211331222113112211", "")
XCTAssertEqual(countAndSay(15), "311311222113111231131112132112311321322112111312211312111322212311322113212221", "")
}
}