阿摩線上測驗 登入

申論題資訊

試卷:114年 - 114 經濟部所屬事業機構_新進職員甄試_資訊:1.資訊管理 2.程式設計#133510
科目:國營事業◆1.資訊管理 2.程式設計
年份:114年
排序:0

申論題內容

四、定義「快樂數」為一個正整數 N 經過以下過程:
1. 將 N 的每一位數字平方後相加,得到新數字。例如:25 → 2×2+5×5=29
2. 重複此步驟,直到出現下述其中一種結果:
①得到 1,則 N 是快樂數
②進入循環(例如:4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4),則 N 非屬快樂數
請設計一函式 isHappy(int n),並註明所使用的程式語言:(15 分)
輸入:正整數 n (1 ≤ n ≤ 109)
輸出:若 n 是快樂數,回傳 true;否則回傳 false

詳解 (共 1 筆)

詳解 提供者:adamhsu622
#define TRUE  1
#define FALSE 0
typedef int bool;
 
struct node {
    int data;
    struct node *link;
};
 
struct queue {
    struct node *head;
    struct node *tail;
    int len;
};
 
// 初始化 Queue
struct queue Q = {NULL,NULL,0};
 
// 配置節點
struct node *alloc_node(){  
    struct node *p = malloc(sizeof(struct node));
    return p;
}
 
// 將值存入 queue
void enqueue(struct queue *q, int v) {
    struct node *p = alloc_node();
    p->data = v;
    p->link = NULL;
    
    if (q->head == NULL)
        q->head = p;
    else
        q->tail->link = p;
    
    q->tail = p;
    q->len++;
}
 
// 將節點儲存的值從 queue 取出
int dequeue(struct queue *q) {
    if (q->head) {
        int v;
        struct node *p = q->head;
        v = p->data;
        q->head = p->link;
        if (q->head == NULL)
            q->tail = NULL;
        free(p);
        q->len--;
        return v;
    }
    return -1;
}
 
// 計算快樂數過程中,檢查是否進入循環
bool check_dup_value(struct queue *q, int v) {
    int value;
    int i, len = q->len;
 
    // 檢查過程若發現重複,則回傳 TRUE
    // 否則把值重新存入 queue,並檢查下一個
    //
    for (i = 0; i < len; i++) {
        value = dequeue(q);
        if (value == v)
            return TRUE;
        enqueue(q,value);
    }
    enqueue(q, v);
    return FALSE;
}
 
// 計算快樂數,若為真則回傳 TRUE,否則回傳 FALSE
bool ishappy(int n) {
    bool ret = FALSE;
    int q,r,v = n;
 
    if (v < 0) 
        return ret;
    
    while(1) {
        int temp = 0;
 
        // 取出每一個位數,並進行平方求值再加總
        while(1) {            
            q = v / 10;
            r = v % 10;
            temp += r*r;
            if (q < 10) {
                v = temp + q*q;
                break;
            }
            v = q;
        }
 
        // 加總結果若為 1,則為快樂數並離開
        if (v == 1) {
            ret = TRUE;
            break;
        }
 
        // 判斷加總結果是否出現重複,若是則離開
        if (check_dup_value(&Q, v) == TRUE)
            break;
    }
    return ret;
}
ㅤㅤ
ㅤㅤ
附註:
此題為 leetcode 裡面的一個題目