Skip to content

Commit

Permalink
Go solution for Leetcode 202 Happy Number
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhiwakar92 committed Jun 1, 2022
1 parent db1b275 commit e6e2a48
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions go/202-Happy-Number.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
func isHappy(n int) bool {

total := 0
alreadySeen := make(map[int]bool)
for {

// if we have seen this number
if seen := alreadySeen[n]; seen {
break
}

alreadySeen[n] = true

// split n into its individual digits.
strn := fmt.Sprint(n)

// get the length
length := len(strn)

// compute sum of digits
for i := 0; i < length; i++ {
digit, _ := strconv.Atoi(string(strn[i]))
total += (digit * digit)
}
if total == 1 {
return true
}

// reassign n to total
n = total
total = 0
}

return false
}

0 comments on commit e6e2a48

Please sign in to comment.