• 将数字的每一位取变量(写递归时的步骤)


    法一:正常顺序思路

    #include <iostream>

    #include <cstdio>

    using namespace std;

    int main()

    {

        int a;

        cin>>a;

        while(a%10!=0)  //循环结束条件

        {

            cout<<a%10<<" ";

            a=a/10;

        }

        return 0;

    }

    法二:递归方法1

    #include <iostream>

    #include <cstdio>

    using namespace std;

    int fun(int a)  //单元:把传入的参数的最后一位输出

    {

        if(a==0) return 0;   //递归终止的条件(考虑递归之后添加的代码)(2nd)

        if(a>0)             //功能单元所需的代码(1st)

            cout<<a%10<<" ";    //功能单元所需的代码(1st)

        fun(a/10);              //(考虑递归之后添加的代码:重复的功能单元)(2nd)

    }

    int main()

    {

      int n; cin>>n;

        fun(n);

        return 0;

    }

    法三:递归方法2

    #include <iostream>

    #include <cstdio>

    using namespace std;

    int fun(int a)  //功能单元:输出传入参数的最高位

    {

        if(a==0) return 0;      //写完功能单元以后,回头补充递归终止的条件

        int b=a;

        int i=0;

        while((a/10)%10!=0) //fun的功能单元:输出传入参数的最高位(在写递归的时候,必须把这一步实现出来)

        {

            a=a/10;

            i++;

        }

        cout<<a<<" ";       //fun的功能单元到此结束

        int s=1;            //为写递归做出准备

        for(int j=0;j<i;j++)

            s*=10;

        fun(b-a*s);         //b-a*s是下次递归需要的参数

    }

    int main()

    {

        int n; cin>>n;

        fun(n);

        return 0;

    }

    这篇文章,是又一个故事的结束...
    lazy's story is continuing.
  • 相关阅读:
    [NOI2004] 郁闷的出纳员
    对象内部套嵌多个对象
    函数
    匿名函数、对象
    函数部分
    Html部分
    搜索二叉树的应用
    二叉树的线索化
    搜索结构搜索二叉树
    堆与最优级队列
  • 原文地址:https://www.cnblogs.com/Hello-world-hello-lazy/p/12589047.html
Copyright © 2020-2023  润新知