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

 

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;
}

 

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值