Merge pull request #153 from brenobaptista/suggestion-202

Suggestion 202
This commit is contained in:
halfrost
2021-06-26 17:34:18 +08:00
committed by GitHub
2 changed files with 38 additions and 23 deletions

View File

@ -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
}

View File

@ -35,6 +35,16 @@ func Test_Problem202(t *testing.T) {
para202{19},
ans202{true},
},
{
para202{2},
ans202{false},
},
{
para202{3},
ans202{false},
},
}
fmt.Printf("------------------------Leetcode Problem 202------------------------\n")