递归问题 研究

汉诺塔问题

#include<iostream>
using namespace std;
int cnt;
void hanoi(int n, char from, char by, char to){
    if(n==1){
        cout<<"move "<<n<<" "<<from<<" -> "<<to<<endl;
        cnt++;
    }else{
        hanoi(n-1, from, to, by);
        cout<<"move "<<n<<" "<<from<<" -> "<<to<<endl;
        cnt++;
        hanoi(n-1, by, from, to);
    }
}

int main(){
    int n;
    cin>>n;
    hanoi(n, 'A', 'B', 'C');
    cout<<cnt<<endl;
    return 0;
}

2的幂次表示问题

#include<iostream>
#include<cmath>
using namespace std;

void mici(int n){
    int d[20]={0}, len=0;
    while(n){
        d[len++]=n%2;
        n/=2;
    }
    len--;
    int flag=1;
    for(int i=len; i>=0; i--)
        if(d[i]){
            if(i>=2){
                if(flag){
                    cout<<"2(";
                    flag=0;
                }
                else
                    cout<<"+2(";
                //////////////
                mici(i);
                //////////////
                cout<<")";
            }else{
                if(i==1)
                    if(flag){
                        cout<<2;
                        flag=0;
                    }else
                        cout<<"+2";
                if(i==0)
                    if(flag){
                        cout<<"2(0)";
                        flag=0;
                    }else
                        cout<<"+2(0)";
            }
        }
}

int main(){
    int n;
    cin>>n;
    mici(n);
    return 0;
}

逆博兰表达式问题

#include<iostream>
#include<cmath>
using namespace std;

double nbl(){
    char st[100];
    scanf("%s", st);
    if(st[0]>='0' && st[0]<='9'){
        return atof(st);
    }else{
        double lval=nbl();
        double rval=nbl();
        if(st[0]=='+')  return lval+rval;
        if(st[0]=='-')  return lval-rval;
        if(st[0]=='*')  return lval*rval;
        if(st[0]=='/')  return lval/rval;
    }
}

int main(){
    cout<<nbl();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/haoff_20/article/details/81745905