[Java] method usage and recursion

Posted by ifuschini on Fri, 14 Jan 2022 15:25:38 +0100

Write in front: Hello everyone, I'm a rookie xiaopang p. Today's blog is a Java method. Method is actually a function of c language. The article also mentioned overloading. We should pay attention to distinguish overloading and rewriting (which will also be mentioned later). In addition, recursion is also introduced. About the blog content, if you don't understand, you can also leave a message in the comment area. You don't know much, but you don't say anything. Limited ability, where there are mistakes, welcome to correct!

First knowledge method

Methods in Java are similar to functions in c language

Observe the following code to realize the benefits of this method.

//Find the maximum of two numbers
public static int maxTwoNum(int a,int b) {
    return a>b ? a : b;
}
//Find the maximum of three numbers
public static int maxThreeNum(int a,int b,int c) {
    int max=maxTwoNum(a,b);
    return maxTwoNum(max,c);
}
public static void main(String[] args) {
    int a=10,b=23,c=4;
    System.out.println(maxThreeNum(a,b,c));

Flexible use of methods can reduce repeated code and make the code simpler.

Relationship between arguments and formal parameters

In Java, only by value is passed

Analyze the following code: swap two integer variables

public static void swap(int x,int y){
    int tmp=x;
    x=y;
    y=tmp;
}
public static void main5(String[] args) {
    //Error demonstration of exchanging two integer variables
    int a=10;
    int b=20;
    swap(a,b);
    System.out.println(a);
    System.out.println(b);
}

The output result is 10 20, and the exchange of two numbers is not completed. For a base type, a formal parameter is equivalent to a copy of an argument Value passing call

public static void swap1(int[] arr){
    int tmp=arr[0];
    arr[0]=arr[1];
    arr[1]=tmp;
}
public static void main(String[] args) {
    //The correct way to swap two integers
    int[] arr={10,20};
    swap1(arr);
    System.out.println(Arrays.toString(arr));
}

Solution: pass reference type parameters, such as arrays.

Exercise: sum n factorials

public static int add(int n) {
    int j=1;
    int sum=0;
    for(j=1;j<=n;j++){
        sum += factor(j);
    }
    return sum;
}
public static int factor(int j){
    int i=1;
    int rst=1;
    for(i=1;i<=j;i++){
        rst *= i;
    }
    return rst;
}
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int num=scan.nextInt();
    System.out.println(add(num));
}

Method overload:

The same method name, which provides different versions of implementations, is called method overloading

  • Same method name
  • The return value is not required
  • Different parameter lists (different number of parameters or parameter types)
  • In the same class
public static int sum(int a,int b) {
    return a+b;
}
public static double sum(double a,double b) {
    return a+b;
}
public static void main(String[] args) {
    System.out.println(sum(4,6));
}

Interview question: the difference between overloading and rewriting

Recursion of method

When a method calls itself in the process of execution, it is called "recursion".

Recursion resolves a big problem into a small problem. To solve the recursion problem, we should find the termination condition and recursion formula.

Find the factorial of n

public static int factor(int n) {
    if(n==1){
        return 1;
    }else {
        return n * factor(n - 1);
    }
}
public static void main(String[] args) {
    System.out.println(factor(4));
}

Find the sum of n factorials

public static int factor(int i){
    if(i==1){
        return 1;
    }else{
        return i*factor(i-1);
    }
}
public static void main(String[] args) {
    int sum=0;
    Scanner scan = new Scanner(System.in);
    int num=scan.nextInt();
    for (int i = 1; i < num; i++) {
        sum+= factor(i);
    }
    System.out.println(sum);
}

Print each bit of a number in sequence (for example, 1234 prints 1 2 3 4)

public static void func(int n) {
    if(n>9){
        func(n/10);
    }
    System.out.print(n%10+" ");
}
public static void main(String[] args) {
    func(123);
}

Recursively find 1 + 2 + 3 +... + 10

public static int sum(int n) {
    if (n==1) {
        return 1;
    } else {
        return n+sum(n-1);
    }
}
public static void main(String[] args) {
    System.out.println(sum(10));
}

Write a recursive method, enter a nonnegative integer, and return the sum of the numbers that make up it

For example, if you enter 1729, you should return 1 + 7 + 2 + 9, and its sum is 19

public static int func(int n) {
    if(n>9){
        return n%10+func(n/10);
    }
    return n;
}
public static void main(String[] args) {
    System.out.println(func(5211));
}

Find the nth item of Fibonacci sequence:

public static int fib(int n) {
 if (n == 1 || n == 2) {
 return 1;
 }
 return fib(n - 1) + fib(n - 2);
} 

Recursive implementation of Fibonacci sequence is not recommended, but loop is recommended.

public static int func(int n) {
    int n1=1;
    int n2=1;
    int n3=1;
    for(int i=3;i<=n;i++) {
        n3=n1+n2;
        n1=n2;
        n2=n3;
    }
    return n3;
}
public static void main(String[] args) {
    System.out.println(func(1));
}

Tip: when thinking about recursion, think horizontally and don't expand recursive code

Topics: Java Back-end