打卡cs106x(Autumn 2017)-lecture6
(以下皆使用SPL实现,非STL库,后续课程结束会使用STL实现)
1、setMystery
What is the output of the following code?
解答:
{9, 12, 32, 999}
2、wordCount
Write a function named wordCount
that accepts a file name as a parameter and opens that file and that returns a count of the number of unique words in the file. Do not worry about capitalization and punctuation; for example, "Hello" and "hello" and "hello!!" are different words for this problem. Use a Set
as auxiliary storage.
解答:
int wordCount(string filename) {
Set<string> s;
string word;
ifstream input;
input.open(filename);
if (input.is_open()) { // 是否打开文件
while (input >> word) {
s.add(word);
}
}
input.close();
return s.size();
}
3、isHappyNumber
Write a function named isHappyNumber
that returns whether a given integer is "happy". An integer is "happy" if repeatedly summing the squares of its digits eventually leads to the number 1.
For example, 139 is happy because:
- 12 + 32 + 92 = 91
- 92 + 12 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
By contrast, 4 is not happy because:
- 42 = 16
- 12 + 62 = 37
- 32 + 72 = 58
- 52 + 82 = 89
- 82 + 92 = 145
- 12 + 42 + 52 = 42
- 42 + 22 = 20
- 22 + 02 = 4
- ...
解答:
#include <iostream>
#include "console.h"
#include "set.h"
using namespace std;
bool isHappyNumber(int n);
int main() {
cout << isHappyNumber(139) << endl;
cout << isHappyNumber(4) << endl;
return 0;
}
bool isHappyNumber(int n) {
Set<int> s;
while (n != 1) { // 求各位的平方和
int result = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
result += d * d;
}
if (s.contains(result)) { // 若重复出现,将进入无限循环
return false;
}
s.add(result);
n = result;
}
return true;
}
4、mapMystery
What is the output of the following code?
解答: