Java elementary basic brush questions

School closure =========== 

content

1. Happy Numbers

2. Ugly numbers

3. Add up everyone


1. Happy Numbers (the idea of ​​a linked list)

202. Happy Numbers - LeetCode (leetcode-cn.com) icon-default.png?t=M1L8https://leetcode-cn.com/problems/happy-number/

Topics and requirements:

Problem solving ideas:

① Divided into two cases: a. The result is 1 (that is, the happy number)

                             b. It is the case of the reciprocating cycle (infinite loop, think of a circular linked list)

② Two pointers, one fast and one slow, are set in the circular linked list (slow is one step at a time, fast is two steps at a time)

③ If slow and fast meet, then it means that it is an infinite loop, that is, a non-happy number

④If fast==1, the fast reaches 1, which means that the slow must also reach 1, which is the happy number

 

code show as below:

class Solution {
    public int sqartNum(int n){
int m=0;
while(n>0){
    m+=(n%10)*(n%10);
    n/=10;
}
return m;
    }
    public boolean isHappy(int n) {
int slow=n;
int fast=sqartNum(n);
while(slow!=fast&&fast!=1){
    slow=sqartNum(slow);
    fast=sqartNum(sqartNum(fast));
} return fast==1;
}
}

2. Ugly numbers

263. 丑数 - 力扣(LeetCode) (leetcode-cn.com)icon-default.png?t=M1L8https://leetcode-cn.com/problems/ugly-number/comments/

Topics and requirements:

 

Problem solving ideas:

①Convert a prime factor into n% of a prime factor = 0;

②Use recursion to transform the problem

code show as below:

class Solution {
    public boolean isUgly(int n) {
        if(n==0)return false;
        if(n==1)return true;
        if(n%2==0){
            return isUgly(n/2);
        }if(n%3==0){
          return   isUgly(n/3);
        }if(n%5==0){
            return isUgly(n/5);
        }return false;
    }
}

3. Add up everyone

258. Add everyone - LeetCode (leetcode-cn.com) icon-default.png?t=M1L8https://leetcode-cn.com/problems/add-digits/submissions/

Topics and requirements:

Problem solving ideas:

①To know how to find the number in the one place; n%10;

② To know how to convert n digits into n-1 digits, n/10;

code show as below:

class Solution {
    public int addDigits(int num) {
while(num/10>=1){
    int m=0;
      m+=num/10+num%10;
      num=m;
}return num;
    }
}

Thanks for watching~

 

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/123113495