[Rookie Training] Sword Finger Offer 64 Seeking 1+2+…+n (logical operator)

Title description:

Seek 1+2+…+n. It is required that keywords such as multiplication and division, for, while, if, else, switch, case and conditional judgment statements (A?B:C) cannot be used.

Example 1:
Input: n = 3
Output: 6

Example 2:
Input: n = 9
Output: 45

Restrictions:
1 <= n <= 10000
Source: LeetCode
Link: https://leetcode-cn.com/problems/qiu-12n-lcof
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving ideas:

Without restrictions, we have many ways to solve this problem, such as: arithmetic sequence summation formula, iteration, recursion, etc. But this question restricts us from using multiplication and division, so the summation formula cannot be used. For and while cannot be used, so iteration cannot be used. What about the remaining recursion? As we all know, recursion needs to be exported. Generally, if and conditional judgment sentences are used for exporting, can other methods be used for exporting?

Before introducing the solution, first review a piece of knowledge. The logical operators && and || have a short-circuit effect, a&&b, when a is false, the system will not verify whether b is false, because no matter what it is, it will not change the result of a&&b. a||b, when a is true, the system will not verify whether b is true, because no matter what it is, it will not change the result of a||b.

So in this problem, can we use logical operators to solve it, of course, when we put the recursive statement to the right of && and the recursive exit to the left, when the exit is false, the system will not go Look at the right end of &&, so the program will not recurse. This satisfies our needs.

Code:

public class jianzhi_Offer_64 {
    
    
    public int sumNums(int n) {
    
    
    //注意此处必须为语句,所以我们可以造一个无关紧要的变量
    //逻辑与算符两端需要时boolean变量
        boolean flag =  (n != 0)&& ((n += sumNums(n - 1))!=0);
        return n;
    }



    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        jianzhi_Offer_64 obj = new jianzhi_Offer_64();
        System.out.println(obj.sumNums(n));
    }
}

Note: You can also use the constructor to solve.

Guess you like

Origin blog.csdn.net/Puppet__/article/details/115033872