HappyNumberOPT [source code]


public class HappyNumberOPT {
static

public class Solution {
    public boolean isHappy(int n) {
        Set<Integer> inLoop = new HashSet<Integer>();
        int squareSum,remain;
        while (inLoop.add(n)) {
            squareSum = 0;
            while (n > 0) {
                remain = n % 10;
                squareSum += remain *remain;
                n /= 10;
            }
            if (squareSum == 1) return true;
            else n = squareSum;
        }
        return false;
    }
}

    public static void main(String[] args) {
        HappyNumberOPT.Solution tester = new HappyNumberOPT.Solution();
        System.out.println(tester.isHappy(Integer.parseInt(args[0])));
    }
}

这个是另外一个 discussion 上面看到的解. 思路还是基于cycle detection, 然后用的思路也更简单, 直接就用 set 来做. 这里要熟悉set.add的返回值. 速度倒是不怎么样, 只有4(58).


Problem Description

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: 19 is a happy number

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

Difficulty:Easy
Category:Algorithms
Acceptance:40.36%
Contributor: LeetCode
Companies
uber airbnb twitter
Related Topics
hash table math
Similar Questions
Add Digits Ugly Number

results matching ""

    No results matching ""