{"id":7,"date":"2025-07-16T09:17:29","date_gmt":"2025-07-16T09:17:29","guid":{"rendered":"https:\/\/bitwonton.com\/?p=7"},"modified":"2025-07-16T09:17:29","modified_gmt":"2025-07-16T09:17:29","slug":"writing-an-algorithm-to-determine-if-a-number-is-happy-using-python","status":"publish","type":"post","link":"https:\/\/bitwonton.com\/?p=7","title":{"rendered":"Writing an algorithm to determine if a number is happy using Python"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Morgan Ho<\/h2>\n\n\n\n<h2 class=\"wp-block-heading\">2025\/06\/13<\/h2>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"leetcode\">Leetcode<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Leetcode is an interview question bank for coding, which appears in varius tech companies. Today I will share how I tackle one of the questions.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"the-question\">The question<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">The question asks me to write an algorithm to determine if a number is happy. A happy number is a number defines by the following process:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Starting with any positive integer, replace the number by the sum of the squares of its digits.<\/li>\n\n\n\n<li>Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.<\/li>\n\n\n\n<li>Those numbers for which this process ends in 1 are happy.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">In short, write some code that returns true if n is a happy number, and false if not.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example 1:<br>Input: n = 19<br>Output: true<br>Explanation:<br>1^2 + 9^2 = 82<br>8^2 + 2^2 = 68<br>6^2 + 8^2 = 100<br>1^2 + 0^2 + 0^2 = 1<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example 2:<br>Input n = 2<br>Output: false<br>Explanation:<br>2^2 = 4<br>4^2 = 16<br>1^2 + 6^2 = 37<br>3^2 + 7^2 = 58<br>5^2 + 8^2 = 89<br>8^2 + 9^2 = 145<br>1^2 + 4^2 + 5^2 = 42<br>4^2 + 2^2 = 20<br>2^2 = 4<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"my-approach-to-the-problem\">My approach to the problem<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s start out with something easy. First, I create a variable \u2019total\u2019 to calculate the sum of the squares of its digits for 1 iteration.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Solution:\n    def isHappy(self, n: int) -&gt; bool:\n        total = 0\n        # find the number of digits of a number.\n        length = len(str(n)) \n        # do a for loop for the amount of times equal to the digits a number has.\n        for i in range (length):\n            # a number with modulus 10 is the last digit. Square it.\n            total += (n%10)**2\n            # integer division by 10 to find the second last digit, third last and so on.\n            n = n\/\/10\n        n = total\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">I have used \u2019total\u2019 to store the first process of summation of squaring all the digits. However, we need to repeat the process. Using another for loop to repeat it 10 times first and view the results using print(). It will be changed to while loop after conditions of breaking the loop is set.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Solution:\n    def isHappy(self, n: int) -&gt; bool:\n        # repeat 10 times as placeholder\n        for j in range(10):\n            total = 0\n            # find the number of digits of a number.\n            length = len(str(n)) \n            # do a for loop for the amount of times equal to the digits a number has.\n            for i in range (length):\n                # a number with modulus 10 is the last digit. Square it.\n                total += (n%10)**2\n                # integer division by 10 to find the second last digit, third last and so on.\n                n = n\/\/10\n            # repeat the same process with previous result \n            n = total\n            print(total)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then, I add a flag to show if a number is happy number. It starts with False and change to true if total equals to 1.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Solution:\n    def isHappy(self, n: int) -&gt; bool:\n        ishappynumber = False\n        # repeat 10 times as placeholder\n        for j in range(10):\n            total = 0\n            # find the number of digits of a number.\n            length = len(str(n)) \n            # do a for loop for the amount of times equal to the digits a number has.\n            for i in range (length):\n                # a number with modulus 10 is the last digit. Square it.\n                total += (n%10)**2\n                # integer division by 10 to find the second last digit, third last and so on.\n                n = n\/\/10\n            # repeat the same process with previous result\n            n = total\n            print(total)\n            if total == 1:\n                ishappynumber = True\n                break\n        return ishappynumber\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Writing a break condition if a number is not happy is more challenging. Most online solutions will use an if statement for n&lt;10 because only 1 or 7 will return happy number. To me, the code should be making calculation for any number \u2019n\u2019, not just hardcoding logic for all numbers under 10. Therefore, my method will check if the number (not equal to 1) has appeared on the list of totals repeatedly. If so, the number is unhappy and the while loop is broken.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Solution:\n    def isHappy(self, n: int) -&gt; bool:\n        ishappynumber = False\n        # initialise the list of totals \n        recordtotal = &#91;]\n        # infinite loop\n        while True:\n            total = 0\n            # find the number of digits of a number.\n            length = len(str(n)) \n            # do a for loop for the amount of times equal to the digits a number has.\n            for i in range (length):\n                # a number with modulus 10 is the last digit. Square it.\n                total += (n%10)**2\n                # integer division by 10 to find the second last digit, third last and so on.\n                n = n\/\/10\n            # repeat the same process with previous result\n            n = total\n            print(total)\n            if total == 1:\n                ishappynumber = True\n                break\n            if total in recordtotal:\n                break\n            recordtotal.append(total)\n        return ishappynumber\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Although it is slower for the program to calculate if a number is happy, it is less hard coded and shows results based on calculation.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Morgan Ho 2025\/06\/13 Leetcode Leetcode is an interview question bank for coding, which appears in varius tech companies. Today I will share how I tackle one of the questions. The question The question asks me to write an algorithm to determine if a number is happy. A happy number is a number defines by the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-7","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/bitwonton.com\/index.php?rest_route=\/wp\/v2\/posts\/7","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bitwonton.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bitwonton.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bitwonton.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bitwonton.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=7"}],"version-history":[{"count":1,"href":"https:\/\/bitwonton.com\/index.php?rest_route=\/wp\/v2\/posts\/7\/revisions"}],"predecessor-version":[{"id":8,"href":"https:\/\/bitwonton.com\/index.php?rest_route=\/wp\/v2\/posts\/7\/revisions\/8"}],"wp:attachment":[{"href":"https:\/\/bitwonton.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=7"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bitwonton.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=7"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bitwonton.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=7"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}