A happy number is a number defined by the following process:
Return true
if n
is a happy number, and false
if not.
True
if the number is a happy number, False
otherwise.To determine if a number is a happy number:
Cycle Detection: Use the concept of detecting cycles in a sequence since if a number loops endlessly in a cycle (other than 1), it is not a happy number.
Set for History: Utilize a set to keep track of numbers that we have already seen in the process. If we encounter a number that is already in the set, we are in a cycle and can return False
.
1
, return True
.False
.def isHappy(n: int) -> bool:
def get_next(number):
total_sum = 0
while number > 0:
digit = number % 10
total_sum += digit * digit
number //= 10
return total_sum
seen = set() # To track already seen numbers to detect cycles
while n != 1 and n not in seen:
seen.add(n)
n = get_next(n)
return n == 1
# Example usage
print(isHappy(19)) # Output: True, because 19 is a happy number
print(isHappy(2)) # Output: False, because 2 is not a happy number
d
is the number of digits in n
and Φ is the happy number process’s duration until it halts.
This approach ensures efficient detection of happy numbers, taking advantage of cycle detection in sequences.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?