UVA - 10591 Happy Number

Posted BobHuang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA - 10591 Happy Number相关的知识,希望对你有一定的参考价值。

Happy Number

 UVA - 10591

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 109.

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.

这道题的递归或者说是循环我感觉挺好的,说实话第一遍我都没看懂这个题,就是给你一个数,如果这个数每个数字的平方和是1就是happy的,手动试了下,小于10的只有1满足,所以我只要把它平方和到一位数就行了,要不然这个循环走不出来,然后继续循环递归就行了

#include <stdio.h>
int f(int b)
{
    int s=0;
    while(b)
    {
        int t=b%10;
        s+=t*t;
        b/=10;
    }
    if(s<10)return s;
    else return f(s);
}
int main()
{
    int T;
    scanf("%d",&T);
    for(int i=1; i<=T; i++)
    {
        int x;
        scanf("%d",&x);
        printf("Case #%d: %d is a",i,x);
        if(f(x)==1)
            printf(" Happy number.\n");
        else printf("n Unhappy number.\n");

    }
    return 0;
}

 

以上是关于UVA - 10591 Happy Number的主要内容,如果未能解决你的问题,请参考以下文章

Uva破损的键盘

leetcode 202. Happy Number 判断一个数是否是“Happy Number” ---------- java

未知来源Happy

LeetCode----202. Happy Number(Java)

LeetCode Happy Number

sqlserver2005如何把row_numbe函数的值赋值给某一列