求 1+2+3+...+n --剑指offer

题目描述

求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路一:递归求1+2+...+n 递归的结束语句用短路&&
public class Solution {
    public int Sum_Solution(int n) {
        int sum=0;
        boolean flag=n>0  && (sum +=n + Sum_Solution(n-1)) > 0;
        return sum;
    }

}

思路二:类似于快速幂计算 a*b

先写出原方法

public class Solution {
    public int Sum_Solution(int n) {
        int a = n;
        int b = n+1;
        int sum=0;
        while (a != 0){
            if((a & 1) == 1) sum += b;
            a >>= 1;
            b <<= 1;
        }
        return  sum >> 1;
    }
 
}

用&&和递归改进后的

public class Solution {
    public int Sum_Solution(int n) {
        return sum(n,n+1) >> 1;
    }
    private int sum(int a,int b){
            int sum=0;
            boolean is1=(a & 1) == 1 && (sum += b) > 0;
            a >>= 1;
            b <<= 1;
            boolean is2=(a != 0)&&(sum +=sum(a,b))>0;
            return sum;
    }

}

 && 前边就相当于条件 只有前边符合才可以进行下边的运算

 
原文地址:https://www.cnblogs.com/nlw-blog/p/12458538.html