Skip to content

Latest commit

 

History

History
executable file
·
78 lines (73 loc) · 2.08 KB

202. Happy Number.md

File metadata and controls

executable file
·
78 lines (73 loc) · 2.08 KB

202. Happy Number

Question

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.

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

Thinking:

  • Method:
    • 使用递归,将不符合的所有数字都加入集合中。
    • 如果碰到了集合中的数字则返回false。
    • 如果碰到了正确的就返回true。
class Solution {
    public boolean isHappy(int n) {
        Set<Integer> s = new HashSet<>();
        return isHappy(n, s);
    }
    private boolean isHappy(int n, Set<Integer> s){
        if(s.contains(n)) return false;
        else{
            s.add(n);
            int cur = 0;
            int remain = 0;
            int sum = 0;
            while(n != 0){
                remain = n % 10;
                n /= 10;
                sum += Math.pow(remain, 2);
            }
            if(sum == 1) return true;
            else{
                return isHappy(sum, s);
            }
        }
    }
}

二刷

  1. 二刷使用了循环,还是要用一个set去存储已经访问的数字。
class Solution {
    public boolean isHappy(int n) {
        if(n <= 0) return false;
        Set<Integer> visited = new HashSet<>();
        List<Integer> temp = null;
        while(!visited.contains(n)){
            visited.add(n);
            temp = new ArrayList<>();
            getDigits(temp, n);
            int count = 0;
            for(Integer d : temp){
                count += d * d;
            }
            if(count == 1) return true;
            n = count;
        }
        return false;
    }
    
    private void getDigits(List<Integer> list, int n){
        while(n != 0){
            list.add(n % 10);
            n /= 10;
        }
    }
}