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