mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
Suggestion for solution 202
This commit is contained in:
@ -1,27 +1,32 @@
|
||||
package leetcode
|
||||
|
||||
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
|
||||
}
|
||||
func getSquareOfDigits(n int) int {
|
||||
squareOfDigits := 0
|
||||
temporary := n
|
||||
|
||||
for temporary != 0 {
|
||||
remainder := temporary % 10
|
||||
squareOfDigits += remainder * remainder
|
||||
temporary /= 10
|
||||
}
|
||||
|
||||
return squareOfDigits
|
||||
}
|
||||
|
||||
func isHappy(n int) bool {
|
||||
record := map[int]int{}
|
||||
|
||||
for n != 1 {
|
||||
record[n] = n
|
||||
|
||||
n = getSquareOfDigits(n)
|
||||
|
||||
for _, previous := range record {
|
||||
if n == previous {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
Reference in New Issue
Block a user