跳到正文

个人记录

T655308 【第一关 找到浮木】快乐数 | U598074 【第一关 找到浮木】快乐数 题解

structzuoye约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

C++
#include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

int sumOfSquares(int n) {
    int sum = 0;
    while (n > 0) {
        int digit = n % 10;
        sum += digit * digit;
        n /= 10;
    }
    return sum;
}
bool isHappyNumber(int n) {
    unordered_set<int> seen;
    while (n != 1 && seen.find(n) == seen.end()) {
        seen.insert(n);
        n = sumOfSquares(n);
    }
    return n == 1;
}

int main() {
    int T;
    cin >> T;

    while (T--) {
        int N;
        cin >> N;

        vector<int> numbers(N);
        for (int i = 0; i < N; i++) {
            cin >> numbers[i];
        }

        int father = -1, mother = -1;
        for (int num : numbers) {
            if (isHappyNumber(num)) {
                if (num % 2 == 0 && father == -1) {
                    father = num;
                }
                else if (num % 2 == 1 && mother == -1) {
                    mother = num;
                }
            }
        }

        cout << "father: " << father << " mother: " << mother << endl;
    }

    return 0;
}
原文