top of page

LeetCode 30 day challenge #2

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.



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:

ree

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

Recent Posts

See All
Leetcode may challenge.

Leetcode May challenge had officially started. It started on 5/1 so I'm a few days late, but I'll start doing that one. Unfortunately,...

 
 
 
Sound meter

This is a project that is ongoing in our school's electronic class. The electronic class isn't just any electronic class, but rather we...

 
 
 

Comments


Post: Blog2_Post
bottom of page