zoukankan      html  css  js  c++  java
  • 不用循如何计算数组累加和

      如果将不用循环如何计算1累加到100做一个变化,不再用连续的自然数做累加,而是一个int数组,如何实现呢?思路还是老思路,只不过上次我们是从后往前(由100往下累加到1),现在我们反过来了,是从头往后:

    public class Recursion {
    
        // 数组下标索引,从0开始
        private static int count = 0;
    
        // 递归的退出条件是下标索引=数组长度-1,此时返回数组值
        public static int add(int[] toAdds, int index) {
            if (count < toAdds.length - 1) {
                return toAdds[count] + add(toAdds, count++);
            }
    
            return toAdds[count];
        }
    
        public static void main(String[] args) {
    
            // 还是计算1+...+100
            int[] toAdds = new int[100];
            for (int i = 0; i < toAdds.length; i++) {
                toAdds[i] = i + 1;
            }
            System.out.println(add(toAdds, count));
    
            // 随便计算一个数组
            toAdds = new int[]{1, 5, 7, 33, 101};
    
            // 重新初始化数组索引
            count = 0;
            System.out.println(add(toAdds, count));
    
        }
    }

      运行结果:

    5050
    147
  • 相关阅读:
    poj 1562 Oil Deposits
    poj 1650 Integer Approximation
    snmp4j 编程
    ubuntu 13.04 163源(亲测可用)
    c语言中static 用法总结(转)
    Spring入门
    Hibernate入门
    Struts2入门教程
    素数距离问题
    ASCII码排序
  • 原文地址:https://www.cnblogs.com/wuxun1997/p/11136373.html
Copyright © 2011-2022 走看看