• 从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

  • 相关阅读:
    apollo实现c#与android消息推送(三)
    apollo实现c#与android消息推送(二)
    apollo实现c#与android消息推送(一)
    成为架构师,需要哪些技能
    Centos 7.x Smokeping部署安装及使用
    ISIS实验配置
    Netty网编程实战:四种解决粘包方式切换、两种生产级双向监听模式并行、高效编解码、多处理器协同作战
    STP+基于LACP的portchannel 实验分享
    Java基础之反射
    IntelliJ IDEA 可以使用中文了
  • 原文地址:https://www.cnblogs.com/aDust/p/Recursion.html
Copyright © 2020-2023  润新知