49. seeking 1 + 2 + 3 + ....... + n

Subject description:

  Evaluation 1 + 2 + 3 + ... + n, require multiplication and division can not be used, as well as, if, while, for other keywords.

Analysis of ideas:

  The solution using recursion, but recursion termination condition is required if the keyword does not meet the requirements, so we use logic and interrupt mechanism to describe recursion termination condition.

  When when n == 0, n> 0 is not satisfied so that the latter does not perform recursive operations.

  When n> 0, we will later perform a recursive operation.

Code:

public class Test{
    public int sum(int n){
        int res=n;
        boolean flag=(n>0)&&((res=res+sum(n-1))>0);
        return res;
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/10935434.html