UVa 10591 - Happy Number

7 篇文章 0 订阅

题意:将给出数各个位上的数字的平方和加起来得到新的数字,依次往下推新数字,直到得到得到数字1(Happy number)或是与之前重复的数字(unhappy number)。

利用哈希表查找判重或是直接打表,因为输入最大是10的9次方的数字,因此得出的数字最大为9*9*9 = 729。

代码一(hash 0.020s):

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>

using namespace std;
const int MaxSize  = 850;
int head[MaxSize], next[MaxSize];
int solve(int n)
{
    int t, sum = 0;
    while(n)
    {
        t = n % 10;
        sum += t * t;
        n /= 10;
    }
    return sum;
}
int insert(int s, int h)
{
    int u = head[h];
    while(u)
    {
        if(h == 1)
            return 1;
        if(head[u] == head[s])
            return 2;
        u = next[u];
    }
    next[s] = head[h];
    head[h] = s;
    return 0;
}
int main()
{
#ifdef test
    freopen("sample.txt", "r", stdin);
#endif
    int p, n, flag, cct = 0;
    scanf("%d", &p);
    while(p--)
    {
        int rear = 2;
        scanf("%d", &n);
        printf("Case #%d: %d", ++cct, n);
        memset(head, 0, sizeof(head));
        n = solve(n);
        while(1)
        {
            flag = insert(rear, n);
            if(!flag)
            {
                n = solve(n);
                ++rear;
            }
            else if(flag == 1)
            {
                printf(" is a Happy number.\n");
                break;
            }
            else if(flag == 2)
            {
                printf(" is an Unhappy number.\n");
                break;
            }
        }
    }
}


代码二(直接打表 0.008s):

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>

using namespace std;
const int MaxSize  = 850;
int head[MaxSize];
int solve(int n)
{
    int t, sum = 0;
    while(n)
    {
        t = n % 10;
        sum += t * t;
        n /= 10;
    }
    return sum;
}
int insert(int n)
{
    int m = n;
    while(1)
    {
        n = solve(n);
        if(n == 1)
            return 1;
        else if(head[n] || n == m)
            return 0;
        head[n] = 1;
    }
    return 0;
}
int main()
{
#ifdef test
    freopen("sample.txt", "r", stdin);
#endif
    int p, n, cct = 0;
    scanf("%d", &p);
    while(p--)
    {
        scanf("%d", &n);
        printf("Case #%d: %d", ++cct, n);
        memset(head, 0, sizeof(head));
        if(insert(n))
            printf(" is a Happy number.\n");
        else
            printf(" is an Unhappy number.\n");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值