UVA10591-Happy Number解法

2018-11-11
1分鐘閱讀

敘述

7 is a Happy number since 7 → 49 → 97 → 130 → 10 → 1
4 is an Unhappy number since 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4

輸入說明

一個正整數

輸出說明

輸出是否為Happy Number

Solution

將執行過的數字記錄下來record[],每次平方後做一次查表,看看有沒有重複做過的數字,如果有重複數字就不是HappyNumber。

將一路上執行過的數字紀錄下來,每次跑下一個數字之前先從頭檢查一遍是否重複,如果有重複數字的話,則為UnhappyNumeber

為什麼不檢查到回到自己?

在測資為數字2的時候,2->4->16….,你會發現2是不會回到自己的!!! 因為4會一直循環,不會回到二,而造成程式陷入無限迴圈

#include<stdio.h>


int deal(int k) {
    int sum = 0;
    while (k) {
        sum += (k % 10) * (k % 10);
        k /= 10;
    }
    return sum;
}

int main() {
    int cases = 0;
    int record[700];
    int temp = 0;
    scanf("%d", &cases);
    for (int j = 1; j <= cases;j++) {
        int count = 0,flag = 0;
        int num = 0;
        scanf("%d", &num);
        temp = num;
        while (num != 1) {
            record[count] = num;
            num = deal(num);
            for (int idx = 0; idx <= count; idx++) {
                if (record[idx] == num) {
                    flag = 1;
                    break;
                }
            }
            if (flag) {

                printf("Case #%d: %d is an Unhappy number.\n",j, temp);
                break;
            }
            count++;
        }
        if(num == 1) 
            printf("Case #%d: %d is a Happy number.\n",j, temp);
    }
    return 0;
}
comments powered by Disqus