TypechoJoeTheme

顿搜

统计

[LeetCode 202] Happy Number [Java] [Runtime : 5MS]

2017-09-02
/
0 评论
/
494 阅读
/
正在检测是否收录...
09/02

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

2. Runtime Distribution

3. Submission Details

4. Example

19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

5. Code

private HashSet<String> set = new HashSet<String>();

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

    if (n == 1) {
        return true;
    }

    String num = String.valueOf(n);

    if (set.contains(num)) {
        return false;
    }

    set.add(num);

    int sum = 0;
    for (int i = 0; i < num.length(); i++) {
        int tmp = num.charAt(i) - '0';
        sum += tmp * tmp;
    }
    return isHappy(sum);
}

6.Test

import java.util.HashSet;

public class LeetCode0202 {

    private HashSet<String> set = new HashSet<String>();

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

        if (n == 1) {
            return true;
        }

        String num = String.valueOf(n);

        if (set.contains(num)) {
            return false;
        }

        set.add(num);

        int sum = 0;
        for (int i = 0; i < num.length(); i++) {
            int tmp = num.charAt(i) - '0';
            sum += tmp * tmp;
        }
        return isHappy(sum);
    }

    public static void main(String[] args) {
        LeetCode0202 leetcode = new LeetCode0202();
        System.out.println(leetcode.isHappy(19));
    }
}
Math
朗读
赞 · 0
版权属于:

顿搜

本文链接:

https://dun.so/archives/799/(转载时请注明本文出处及文章链接)