zoukankan      html  css  js  c++  java
  • 从1加到N的简单实现

    一直搞web应用层程序开发,基本算法依然忘记干净。

    这不一次去某公司面试,让我用递归写个从1加到N的方法,一时间卡壳,竟然丢份了。

    回来后,在电脑上把方法一写,居然发现如此简单,唉!为了给自己以后警钟,就把这实现记录在此!

    package cn.com.szgr.method;

    public class ArithMetic {

       /**
        * 数学公式实现指定步长step从m加到n
        *
        * @param start
        * @param end
        * @param step
        * @return
        */
        public int Math(int start, int end, int step) {
            return ((end * (end - step) / 2) - (start * (start - step) / 2)) + end;
        }

       /**
        * 递归算法实现指定步长step从m加到n
        *
        * @param start
        * @param end
        * @param step
        * @return
        */
        public int Recursion(int start, int end, int step) {
            int count = start;
            if (start < end) {
                count += Recursion(start + step, end, step);
           }
           return count;
        }

        /**
         * 用循环实现指定步长step从m加到n
        *
        * @param start
        * @param end
        * @param step
        * @return
        */
        public int Repeat(int start, int end, int step) {
            int count = 0;
            for (int i = start; i <= end; i += step) {
                count += i;
           }
            return count;
        }

        public static void main(String[] args) {
            ArithMetic arithMetic = new ArithMetic();
            System.out.println(arithMetic.Recursion(1, 10, 1));
            System.out.println(arithMetic.Repeat(1, 10, 1));
            System.out.println(arithMetic.Math(1, 10, 1));
       }
    }

    程序输出结果为:

    55

    55

    55

  • 相关阅读:
    Linux显示文件内容常用命令
    Linux文件权限和更改权限
    数据存储及恢复的基本原理
    使用jemter发送HTTPS请求
    运行Jmeter时,出现java.util.prefs.WindowsPreferences <init>异常警告
    Server08AD域安装以及推送
    SVN服务器和客户端搭建
    selenium常见操作
    TestNG 入门教程
    ant+TestNG-xslt生成selenium测试报告
  • 原文地址:https://www.cnblogs.com/aDust/p/Recursion.html
Copyright © 2011-2022 走看看