-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
Write an algorithm to determine if a number `n` is happy. | ||
|
||
A **happy number** is a number defined by the following process: | ||
|
||
- Starting with any positive integer, replace the number by the sum of the squares of its digits. | ||
- Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1. | ||
- Those numbers for which this process **ends in 1** are happy. | ||
|
||
Return `true` if `n` _is a happy number, and_ `false` if not. | ||
|
||
**Example 1:** | ||
|
||
``` | ||
Input: n = 19 | ||
Output: true | ||
Explanation: | ||
12 + 92 = 82 | ||
82 + 22 = 68 | ||
62 + 82 = 100 | ||
12 + 02 + 02 = 1 | ||
``` | ||
|
||
**Example 2:** | ||
|
||
``` | ||
Input: n = 2 | ||
Output: false | ||
``` | ||
|
||
**Constraints:** | ||
|
||
- 1 <= n <= 2^31 - 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package main | ||
|
||
import "fmt" | ||
|
||
func main() { | ||
fmt.Println(isHappy(19)) | ||
fmt.Println(isHappy(2)) | ||
} | ||
|
||
func isHappy(n int) bool { | ||
if n == 0 { | ||
return false | ||
} | ||
res := 0 | ||
num := n | ||
record := map[int]int{} | ||
for { | ||
for num != 0 { | ||
res += (num % 10) * (num % 10) | ||
num = num / 10 | ||
} | ||
if _, ok := record[res]; !ok { | ||
if res == 1 { | ||
return true | ||
} | ||
record[res] = res | ||
num = res | ||
res = 0 | ||
continue | ||
} else { | ||
return false | ||
} | ||
} | ||
} |