Skip to main content

Command Palette

Search for a command to run...

Happy Number

Published
2 min read
Happy Number
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

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.

  • 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.

Return true if n is a happy number, and false if not.

LeetCode Problem - 202

class Solution {
    public boolean isHappy(int n) {
        // Set to keep track of the numbers we've seen to detect cycles
        Set<Integer> seen = new HashSet<>();

        // Continue the process until n becomes 1 or we see a repeated number (cycle detection)
        while (n != 1 && !seen.contains(n)) {
            seen.add(n);           // Add the current number to the set of seen numbers
            n = digitSum(n);      // Update n to the sum of the squares of its digits
        }

        // Return true if n is 1 (happy number), otherwise false (not a happy number)
        return n == 1;
    }

    // Helper method to calculate the sum of the squares of the digits of a number
    private int digitSum(int num) {
        int sum = 0;
        // Process each digit of the number
        while (num != 0) {
            int digit = num % 10;      // Extract the last digit of num
            sum += digit * digit;    // Add the square of the digit to sum
            num /= 10;               // Remove the last digit from num
        }
        return sum; // Return the calculated sum
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.