LeetCode 150 classic interview questions -- happy number (simple)

1. Topic

Write an algorithm to determine nwhether a number is a happy number.

"Happy Number"  is defined as:

  • For a positive integer, each time the number is replaced by the sum of the squares of the digits in each position.
  • Then repeat this process until the number becomes 1, or it may be an infinite loop but it will never change to 1.
  • If the result of this process is  1, then the number is a happy number.

Return if nis a happy numbertrue ; if not, return false.

2. Examples

Example 1:

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

Example 2:

Input: n = 2
Output: false


3. Ideas

If you observe the law of the fast and slow pointer method,
         you can find that if it is not a happy number, it will always fall into a cycle. as shown in the picture

At this point, two pointers can be defined, a fast pointer and a slow pointer. The fast pointer can move two frames at a time, and the slow pointer can only move one frame at a time. But both will be encountered in the end. If the fast pointer encounters 1 first, the loop ends or the tortoise and the hare meet. At this time, it is necessary to judge the numbers of the two. If the value encountered is not 1, then it means that there is no happiness. number.

4. Code

LeetCode code

class Solution {
    public boolean isHappy(int n) {
        int slowPointer = n;
        int quickerPointer = getNext(n);
        while (quickerPointer!=1 &&quickerPointer!=slowPointer){
            quickerPointer = getNext(getNext(quickerPointer));
            slowPointer = getNext(slowPointer);
        }
        return quickerPointer==1;
    }
    public int getNext(int n){
        int sum =0;
        while (n>0){
            sum += Math.pow(n%10,2);
            n = n/10;
        }
        return  sum;
    }
}

Time complexity O(logn) Space complexity O(1)

Specific case code:

package LeetCode19;

public class javaDemo {
    public static void main(String[] args) {
        boolean flag ;
        int n = 4;
//        乌龟
        int slowPointer = n;
//        兔子
        int quickerPointer = getNext(n);
//        当兔子不是1或者两者还未相遇的时候则两者继续前进
        while (quickerPointer!=1 &&quickerPointer!=slowPointer){
            quickerPointer = getNext(getNext(quickerPointer));
            slowPointer = getNext(slowPointer);
        }
//        当兔子遇到1或者龟兔相遇时候判断龟兔相遇的时候值是否为1
        flag = quickerPointer==1;
//        输出结果
        System.out.println(flag);
    }
//    计算每一个的数字的平方和
    public static  int getNext(int n){
//        定义累计和
        int sum =0;
        while (n>0){
            sum += Math.pow(n%10,2);
            n = n/10;
        }
        return  sum;
    }
}

Will it? Try to challenge the next question! ♪(^∀^●)ノシ(●´∀`)♪

LeetCode 150 interview classic questions -- summary interval (simple)_Alphamilk's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/dogxixi/article/details/132281709