cs106x-lecture6(Autumn 2017)-SPL实现

打卡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?

 解答:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值