编写一个算法来判断一个数 n
是不是快乐数。
「快乐数」 定义为:
- 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
- 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
- 如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n
是 快乐数 就返回 true
;不是,则返回 false
。
示例 1:
输入:n = 19 输出:true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
示例 2:
输入:n = 2 输出:false
提示:
1 <= n <= 231 - 1
分析:1.逐个获取数字的每一位并且相加,判断概数是否为1,如果为1则return true
2.关键点:如果判断重复数,需要用hash来判断
typedef struct node {
int value;
struct node *next;
} NODE;
typedef struct hash {
NODE **hash_list;
int size;
} HASH;
HASH *hash_init(int size)
{
HASH *hash_head = malloc(sizeof(HASH));
if (hash_head == NULL) {
printf("open space error\n");
exit(0);
}
hash_head->size = size;
hash_head->hash_list = calloc(size, sizeof(NODE *));
if (hash_head->hash_list == NULL) {
exit(0);
}
return hash_head;
}
bool hash_put(HASH *head, int key, int value)
{
int pos = key%head->size;
NODE *now_node = head->hash_list[pos];
NODE *new_node = NULL;
if (head == NULL) {
printf("open space error\n");
exit(0);
}
//遍历查找,如果找到则说明存在,return false
while (now_node) {
if (now_node->value == value) {
return false;
}
now_node = now_node->next;
}
//不存在则put
new_node = malloc(sizeof(NODE));
if (new_node == NULL) {
exit(0);
}
new_node->value = value;
new_node->next = head->hash_list[pos];
head->hash_list[pos] = new_node;
return true;
}
bool isHappy(int n) {
HASH *hash_head = hash_init(100);
int num, sum;
while (n != 1) {
sum = 0;
while (n != 0) {
num = n%10;
n = n/10;
sum += num * num;
}
n = sum;
if (hash_put(hash_head, sum, sum) == false) {
return false;
}
}
return true;
}
或者
#define MAX_LEN 967
typedef struct list {
int key;
struct list *next;
} List;
typedef struct {
List *headList[MAX_LEN];
} HashSet;
HashSet *createHashSet()
{
HashSet *head = malloc(sizeof(HashSet));
if (head == NULL) {
exit(0);
}
memset(head, 0, sizeof(HashSet));
for (int i = 0; i < MAX_LEN; i++) {
head->headList[i] = NULL;
}
return head;
}
bool isInHasSet(List *list, int key)
{
List *head = list;
while (head != NULL) {
if (list->key == key) {
return true;
}
head = head->next;
}
return false;
}
bool myHashSetAdd(HashSet *obj, int key)
{
if (isInHasSet(obj->headList[key%MAX_LEN], key) == true) {
return false;
}
//add
List *newNode = malloc(sizeof(List));
if (newNode == NULL) {
exit(0);
}
memset(newNode, 0, sizeof(List));
newNode->key = key;
newNode->next = NULL;
if (obj->headList[key%MAX_LEN] != NULL) {
newNode->next = obj->headList[key%MAX_LEN];
obj->headList[key%MAX_LEN] = newNode;
}
obj->headList[key%MAX_LEN] = newNode;
return true;
}
bool isHappy(int n) {
HashSet *headHead = createHashSet();
int num, sum;
while (n != 1) {
sum = 0;
while (n != 0) {
num = n%10;
n = n/10;
sum += num * num;
}
n = sum;
if (myHashSetAdd(headHead, sum) == false) {
return false;
}
}
return true;
}