LeetCode 30 day challenge #2
- rexchao
- Apr 18, 2020
- 2 min read
Question prompt:
Happy Number
Write an algorithm to determine if a number n is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Return True if n is a happy number, and False if not.
See more detail at https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3284/
This question seems quite tricky at first because it seems like we have to test something that could potentially cycle endlessly, but it isn't hard to observe that if a happy number doesn't work, it will most likely repeat numbers. Otherwise, if the value ends up as a happy number, it would probably take less than a few tries (obviously this isn't really good implementation, but for this question, it works, and it reduces compilation time)
Here is the implementation:

Let's look at the function f first. This function takes a value and returns an integer. We create a new variable x to store the new value and iterate through the value we take in. Note that it needs to be converted into a string or list before iterating because integers are immutable. So we basically add the square of the digits to x, and return x. Now we have a function that can spit out what we want by giving it a value. Now we do something like 20 tries, if after 20 iterations it still doesn't become 1, we know its not a happy number.
This problem isn't really good because it assumes or it allows using limited iteration, but obviously it is possible to make a solution that uses a while loop. I'll see you in question 3
-Rex

Comments