202. Happy Number (Easy)

https://leetcode.com/problems/happy-number/

Write an algorithm to determine if a number 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.

Example: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Solutions

class Solution {

    // TODO, is there any situation of endless loop that is not caused by duplicating outcomes?

    public boolean isHappy(int n) {
        // corner case: n <= 0
        if (n <= 0) {
            return false;
        }

        // The endless loop is caused by the fact that certain number returns back to itself
        // number after a serials of computations. So keep track of all the resulting numbers 
        // and jump out he loop once repeated computations take place.
        Set<Integer> visited = new HashSet<>();

        int val = n;
        while (true) {
            if (val == 1) {
                return true;
            }

            if (visited.contains(val)) {
                break;
            }

            visited.add(val);

            int tmp = val;
            val = 0;

            while (tmp != 0) {
                val += Math.pow(tmp % 10, 2);
                tmp = tmp / 10;
            }
        }

        return false;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:18

results matching ""

    No results matching ""