十进制与八进制的转换(栈和队列)

Description

对于输入的任意一个非负十进制整数,利用栈打印输出与其等值的八进制数。

Input

111

Output

157

Sample Input

148

Sample Output

224

先转换成2进制  在分3组存到另一个对列中(没理解转换,其实直接对8求余  直接取出就好,就当练手了)

方法一

#include <stdio.h>

#include <string.h>
#include <deque>
#include <algorithm>
#include <iostream>
using namespace std;
deque <int> a,b;
int main()
{
    int n;
    scanf("%d",&n);
    while(n!=0)
    {
        a.push_back(n%2);
        n=n/2;
    }
    int p=a.size()/3;
    int q=a.size()%3;
    if(p==0)
    {
        for(int i=1;i<=p;i++)
        {
            int e=a.front();
            a.pop_front();
            int f=a.front();
            a.pop_front();
            int g=a.front();
            a.pop_front();
            int m=e+f*2+g*4;
            b.push_back(m);
        }
    }
    else
    {
        for(int i=1;i<=p+1;i++)
        {
            if(q!=p+1)
            {int e=a.front();
            a.pop_front();
            int f=a.front();
            a.pop_front();
            int g=a.front();
            a.pop_front();
            int m=e+f*2+g*4;
            b.push_back(m);}
            else
            {
                if(q==1)
                {
                    int e=a.front();
                    a.pop_front();
                    b.push_back(e);
                }
                if(q==2)
                {
                    int e=a.front();
                    a.pop_front();
                    int f=a.front();
                    a.pop_front();
                    b.push_back(e+2*f);
                }
            }
        }
    }
    int s=0,w=1;
    while(1)
    {
        if(b.empty())
            break;
        int x=b.front();
        b.pop_front();
        s+=x*w;
        w*=10;
    }
    printf("%d\n",s);
    return 0;

}

方法二

#include <stdio.h>
#include <string.h>
#include <deque>
#include <algorithm>
#include <iostream>
using namespace std;
deque <int> a,b;
int main()
{
    int n;
    scanf("%d",&n);
    while(n!=0)
    {
        a.push_back(n%8);
        n=n/8;
    }
    int s=0,w=1;
    while(1)
    {
        if(a.empty())
            break;
        int x=a.front();
        a.pop_front();
        s+=x*w;
        w*=10;
    }
    printf("%d\n",s);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zcy19990813/article/details/80869744