浙江大学计算机与软件学院 2019 年保研机考 7-1 Happy Numbers (C++)

A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits in base-ten, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers and the number of iterations is called the degree of happiness, while those that do not end in 1 are unhappy numbers (or sad numbers). (Quoted from Wikipedia)

For example, 19 is happy since we obtain 82 after the first iteration, 68 after the second iteration, 100 after the third iteration, and finally 1. Hence the degree of happiness of 19 is 4.

On the other hand, 29 is sad since we obtain 85, 89, 145, 42, 20, 4, 16, 37, 58, and back to 89, then fall into an endless loop. In this case, 89 is the first loop number for 29.

Now your job is to tell if any given number is happy or not.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N ( ≤ 100 ) N (≤100) N(100). Then N N N lines follow, each contains a positive integer (no more than 1 0 4 10^4 104) to be tested.

Output Specification:

For each given number, output in a line its degree of happiness if it is happy, or the first loop number if it is sad.

Sample Input:

3
19
29
1

Sample Output:

4
89
0

Solution:

// Talk is cheap, show me the code
// Created by Misdirection 2021-09-19 18:53:15
// All rights reserved.

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

int firstLoop, degree;

bool isHappy(int a){
    int cnt = 1;
    if(a == 1){
        degree = 0;
        return true;
    }
    
    unordered_map<int, bool> flag;

    while(true){
        if(flag[a]){
            firstLoop = a;
            return false;
        }

        flag[a] = true;

        int tmp = 0;
        while(a != 0){
            tmp += (a % 10) * (a % 10);
            a /= 10;
        }

        if(tmp == 1){
            degree = cnt;
            return true;
        }
        a = tmp;
        cnt++;
    }
}

int main(){
    int n;
    scanf("%d", &n);

    int num;
    for(int i = 0; i < n; ++i){
        scanf("%d", &num);

        if(isHappy(num)) printf("%d\n", degree);
        else printf("%d\n", firstLoop);
    }

    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

负反馈循环

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值