From 5dc3022bc5c6aa84fdd1ce255fad723200ffe059 Mon Sep 17 00:00:00 2001 From: slaier <30682486+slaier@users.noreply.github.com> Date: Sat, 29 Jul 2023 06:48:13 +0000 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200202=E5=BF=AB=E4=B9=90?= =?UTF-8?q?=E6=95=B0=20C=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0202.快乐数.md | 68 ++++++++++++++++++++++++++++---------- 1 file changed, 50 insertions(+), 18 deletions(-) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index 4a77e2b6..719672a2 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -423,29 +423,61 @@ impl Solution { ### C: ```C -typedef struct HashNodeTag { - int key; /* num */ - struct HashNodeTag *next; -}HashNode; - -/* Calcualte the hash key */ -static inline int hash(int key, int size) { - int index = key % size; - return (index > 0) ? (index) : (-index); -} - -/* Calculate the sum of the squares of its digits*/ -static inline int calcSquareSum(int num) { - unsigned int sum = 0; - while(num > 0) { - sum += (num % 10) * (num % 10); - num = num/10; +int get_sum(int n) { + int sum = 0; + div_t n_div = { .quot = n }; + while (n_div.quot != 0) { + n_div = div(n_div.quot, 10); + sum += n_div.rem * n_div.rem; } return sum; } +// (版本1)使用数组 +bool isHappy(int n) { + // sum = a1^2 + a2^2 + ... ak^2 + // first round: + // 1 <= k <= 10 + // 1 <= sum <= 1 + 81 * 9 = 730 + // second round: + // 1 <= k <= 3 + // 1 <= sum <= 36 + 81 * 2 = 198 + // third round: + // 1 <= sum <= 81 * 2 = 162 + // fourth round: + // 1 <= sum <= 81 * 2 = 162 -Scala: + uint8_t visited[163] = { 0 }; + int sum = get_sum(get_sum(n)); + int next_n = sum; + + while (next_n != 1) { + sum = get_sum(next_n); + + if (visited[sum]) return false; + + visited[sum] = 1; + next_n = sum; + }; + + return true; +} + +// (版本2)使用快慢指针 +bool isHappy(int n) { + int slow = n; + int fast = n; + + do { + slow = get_sum(slow); + fast = get_sum(get_sum(fast)); + } while (slow != fast); + + return (fast == 1); +} +``` + +### Scala: ```scala object Solution { // 引入mutable