zoukankan      html  css  js  c++  java
  • 剑指offer 47.发散思维能力 求1+2+3+...+n

    题目描述

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

    解题思路一

     

    1.需利用逻辑与的短路特性实现递归终止。 2.当n==0时,(n>0)&&((sum+=Sum_Solution(n-1))>0)只执行前面的判断,为false,然后直接返回0

     

    3.当n>0时,执行sum+=Sum_Solution(n-1),实现递归计算Sum_Solution(n)。
     

    代码如下

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

    解题思路二

    代码如下
     public int Sum_Solution(int n) {
            n = (int)(Math.pow(n,2)+n)>>1;
            return n;
        }

     

     

  • 相关阅读:
    python2和python3的区别
    星球大战
    [USACO]高低卡(金)High Card Low Card (Gold)
    学习笔记
    叶子的染色
    大问题
    ...
    考试前...
    [HAOI2010]计数
    [POI2006]OKR-Periods of Words
  • 原文地址:https://www.cnblogs.com/Transkai/p/11387007.html
Copyright © 2011-2022 走看看