求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。


法1.采用递归,利用逻辑与的短路特性

public class Solution {
    int Sum_Solution(int n) {
        int ans = n;
        ans && (ans += Sum_Solution(n - 1));
        return ans;
    }
}

法2. 调用Java库函数

public class Solution {
    public int Sum_Solution(int n) {
        int sum = (int) (Math.pow(n,2) + n);
       return sum>>1;
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM