Sword to Offer-64 求 1+2+3+...+n ❀❀

  • 题目描述:
    1+2+3+...+n,要求不能使用乘除法、forwhileifelseswitchcase等关键字及条件判断语句(A?B:C)

解题思路:

循环的递归写法:
1、n!=0就会继续递归,否则就可出递归,输出sum值了;
2、sum是必定>0的, 加判断只是为了让表达式正确,形如boolean&&boolean;
3、定义boolean类型的变量tmp也是为了语句合理,通过编译,并无任何实际意义。

AC代码:

// Special Way of Writing Loop

public class Solution {
    public int Sum_Solution(int n) {
        int sum = n;
        boolean tmp = (n>0) && ((sum += Sum_Solution(n-1))>0);
        return sum;
    }
}

补充说明:

Comments


yangzail © 2020. All rights reserved.

Powered by Hydejack v8.5.2