求1+2+3+...+n

来源:互联网 发布:编程人生 编辑:程序博客网 时间:2024/06/05 20:26

题目

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

解题

直接求和公式sum=(1+n)n/2,有乘法除法,+-模型*/,需要for
位运算模拟*/ ? 可以吗?

讨论中用逻辑与运算,因为逻辑与具有短路功能,当前面为false后面就不再判断

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

参考上面,模型出乘法和除法,然后根据公式求和

public class Solution {    public int Sum_Solution(int n) {        int sum = n + multiply(n,n);        sum = divide2(sum);        return sum;    }    // 乘法    public int multiply(int a,int b){        int c = a ;        boolean flag = (b>1) && ( (c +=multiply(a,b-1)) >0);        return c;    }    // 除法     public int divide2(int n){        return n>>1;    }}
0 0
原创粉丝点击