Skip to content

Added more readable solution #3035

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 20 additions & 32 deletions go/0202-happy-number.go
Original file line number Diff line number Diff line change
@@ -1,35 +1,23 @@
func isHappy(n int) bool {

total := 0
alreadySeen := make(map[int]bool)
for {
seen := make(map[int]any)
for n != 1 && !contains(seen, n) {
seen[n] = struct{}{}
n = getNext(n)
}
return n == 1
}

// if we have seen this number
if seen := alreadySeen[n]; seen {
break
}
func getNext(num int) int {
totalSum := 0
for num > 0 {
digit := num % 10
totalSum += digit * digit
num /= 10
}
return totalSum
}

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
}
func contains(set map[int]any, val int) bool {
_, ok := set[val]
return ok
}
25 changes: 11 additions & 14 deletions python/0202-happy-number.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
class Solution:
def isHappy(self, n: int) -> bool:
slow, fast = n, self.sumSquareDigits(n)
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = self.getNext(n)
return n == 1

while slow != fast:
fast = self.sumSquareDigits(fast)
fast = self.sumSquareDigits(fast)
slow = self.sumSquareDigits(slow)

return True if fast == 1 else False

def sumSquareDigits(self, n):
output = 0
while n:
output += (n % 10) ** 2
n = n // 10
return output
def getNext(self, num):
total_sum = 0
while num > 0:
num, digit = divmod(num, 10)
total_sum += digit ** 2
return total_sum