mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加 0202快乐数 C 版本
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user