蓝桥杯 基础练习 十六进制转八进制

题目:http://lx.lanqiao.cn/problem.page?gpid=T51

  1 #include <bits/stdc++.h>
  2 using namespace std;
  3 typedef long long ll;
  4 const int N=4*1e5+5;//注意是4倍的长度!
  5 int in[N];
  6 stack<int> st;
  7 string str;
  8 void change()//十六进制转为二进制
  9 {
 10     for (int i=0,j=1;i<str.length();i++)
 11     {
 12         int temp;
 13         switch (str[i])
 14         {
 15         case 'A':
 16             temp=10;
 17             break;
 18         case 'B':
 19             temp=11;
 20             break;
 21         case 'C':
 22             temp=12;
 23             break;
 24         case 'D':
 25             temp=13;
 26             break;
 27         case 'E':
 28             temp=14;
 29             break;
 30         case 'F':
 31             temp=15;
 32             break;
 33         default:
 34             temp=str[i]-'0';
 35         }
 36         if (temp>=8)
 37         {
 38             in[j++]=1;
 39             temp-=8;
 40         }
 41         else
 42         {
 43             in[j++]=0;
 44         }
 45         if (temp>=4)
 46         {
 47             in[j++]=1;
 48             temp-=4;
 49         }
 50         else
 51         {
 52             in[j++]=0;
 53         }
 54         if (temp>=2)
 55         {
 56             in[j++]=1;
 57             temp-=2;
 58         }
 59         else
 60         {
 61             in[j++]=0;
 62         }
 63         if (temp>=1)
 64         {
 65             in[j++]=1;
 66             temp-=1;
 67         }
 68         else
 69         {
 70             in[j++]=0;
 71         }
 72     }
 73 }
 74 void changee()//二进制转为八进制
 75 {
 76     while (!st.empty())//先清空栈
 77     {
 78         st.pop();
 79     }
 80     int len=str.length(),temp;
 81     for (int i=len*4;i>0;)//要从个位倒回去
 82     {
 83         for (int j=1;j<=4;j*=2)
 84         {
 85             if (j==1)
 86             {
 87                 temp=0;
 88             }
 89             if (i<1)//补0的情况,防止越界
 90             {
 91                 temp+=0;
 92             }
 93             else
 94             {
 95                 temp=temp+in[i--]*j;
 96             }
 97         }
 98         st.push(temp);
 99     }
100 }
101 void show()
102 {
103     while (st.top()==0)//清空前导0
104     {
105         st.pop();
106     }
107     while (!st.empty())
108     {
109         printf("%d",st.top());
110         st.pop();
111     }
112     printf("\n");
113 }
114 int main()
115 {
116     int n;
117     scanf("%d",&n);
118     for (int i=0;i<n;i++)
119     {
120         cin>>str;
121         change();
122         changee();
123         show();
124     }
125 
126     return 0;
127 }

 

posted @ 2019-02-18 23:13  hemeiwolong  阅读(307)  评论(0编辑  收藏  举报