Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 50 additions & 18 deletions problems/0202.快乐数.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

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:
```scala
object Solution {
// 引入mutable
Expand Down