#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 裡面的一個題目