题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1532
Time limit: 3.000 seconds

Problem Description

Let the sum of the square of the digits of a positive integer S0 be represented by S1. In a similar way, let the sum of the squares of the digits of S1 be represented by S2 and so on. If Si = 1 for some i ≥ 1, then the original integer S0 is said to be Happy number. A number, which is not happy, is called Unhappy number. For example 7 is a Happy number since 7 → 49 → 97 → 130 → 10 → 1 and 4 is an Unhappy number since 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.

Input

The input consists of several test cases, the number of which you are given in the first line of the input.

Each test case consists of one line containing a single positive integer N smaller than 10^9.

Output

For each test case, you must print one of the following messages:

  • Case #p: N is a Happy number.
  • Case #p: N is an Unhappy number.

Here p stands for the case number (starting from 1). You should print the first message if the
number N is a happy number. Otherwise, print the second line.

Sample Input

3
7
4
13

Sample Output

Case #1: 7 is a Happy number.
Case #2: 4 is an Unhappy number.
Case #3: 13 is a Happy number.

Problem solving report:

Description: 给一个正数s, 然后计算它每一个位上的平方和,得到它的下一个数, 然后下一个数继续及选每位上的平方和……如果一直算下去,出现了1,那这个数就是个Happy Number.如果算下去的过程中出现了一个之前出现过的,那么就不Happy了。
Problem solving: 通过打表就可以发现,一位数只有1满足,所以我只要把它平方和计算到一位数就行了,要不然这个循环就走不出来了,然后继续循环递归就行了。

Accepted Code:

/* 
 * @Author: lzyws739307453 
 * @Language: C++ 
 */
#include <bits/stdc++.h>
using namespace std;
int slove(int n) {
    int ans = 0;
    while (n) {
        int p = n % 10;
        ans +=  p * p;
        n /= 10;
    }
    if (ans < 10)
        return ans;
    else return slove(ans);
}
int main() {
    int t, n, kase = 0;
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        if (slove(n) != 1)
            printf("Case #%d: %d is an Unhappy number.\n", ++kase, n);
        else printf("Case #%d: %d is a Happy number.\n", ++kase, n);
    }
    return 0;
}