蓝桥杯BASIC-12 十六进制转八进制

题目:

 

思路:

先将十六进制数转换成二进制数,再由二进制数转换成八进制

注意当不满位的时候,首部添加0

 

代码:

 1 #include<bits/stdc++.h> 
 2 using namespace std;
 3 int main()
 4 {
 5     int n;
 6     scanf("%d\n",&n);
 7     while(n--)
 8     {
 9         string s1,s2;
10         getline(cin,s1);
11         for(int i=0;s1[i]!='\0';i++)
12         {
13             switch(s1[i])
14             {
15                 case '0': s2+="0000";break;
16                 case '1': s2+="0001";break;
17                 case '2': s2+="0010";break;
18                 case '3': s2+="0011";break;
19                 case '4': s2+="0100";break;
20                 case '5': s2+="0101";break;
21                 case '6': s2+="0110";break;
22                 case '7': s2+="0111";break;
23                 case '8': s2+="1000";break;
24                 case '9': s2+="1001";break;
25                 case 'A': s2+="1010";break;
26                 case 'B': s2+="1011";break;
27                 case 'C': s2+="1100";break;
28                 case 'D': s2+="1101";break;
29                 case 'E': s2+="1110";break;
30                 case 'F': s2+="1111";break;
31             }
32         }
33         while(s2.size()%3!=0)
34         {
35             s2 = "0"+s2;
36         }
37         int i=0;
38         while(i<s2.size()&&(s2[i]-'0')*4+(s2[i+1]-'0')*2+(s2[i+2]-'0')==0) i+=3;
39         if(i==s2.size()) cout<<"0";
40         else
41         {
42             for(;i<s2.size();i+=3)
43             {
44                 printf("%d",(s2[i]-'0')*4+(s2[i+1]-'0')*2+(s2[i+2]-'0'));
45             }
46         }
47         cout<<endl;
48     }
49     return 0;
50 }

 

posted @ 2020-07-05 10:54  真歆若水  阅读(170)  评论(0编辑  收藏  举报