【蓝桥杯】16转换8进制

来源:互联网 发布:旋转矩阵的逆矩阵 编辑:程序博客网 时间:2024/05/21 06:42

  

在题目锦囊中有提到,咱们可以通过2进制为媒介,达到16转8的目的。

   在学习数电逻辑之后,咱们也都知道, 1位16进制可以代表4位2进制, 1位8进制可以代表3位二进制,为此我的代码大题思路就出来了,字符串存储,3位16进制求和入栈输出表示4位8进制,然后出栈输出,于是有了我最开始的代码。

  

#include<iostream>#include<cstring>#include<cstdio>using namespace std;int stack[40000];void transform(string str, int length){        int top = -1;    for(int i = length - 1; i >= 0; i -= 3)    {        int sum = 0;        for(int j = 0; j < 3 && i - j >= 0; j++)        {            int temp = str[i - j] >= '0' && str[i - j] <= '9' ? str[i - j] - '0' : str[i - j] - 'A' + 10;            sum += (temp << (4 * j));        }        stack[++top] = sum;    }    while( stack[top] == 0)    {    top--;    }    for(int i = top; i >= 0; i--)    {        printf("%o", stack[i]);     }    cout<<endl;}int main(){string *str;int n;cin>>n;str = new string[n];for(int i = 0; i < n; i++){cin>>str[i];}for(int i = 0; i < n; i++){transform(str[i], str[i].size());}return 0;}


 

但是很可惜的是,在评测平台上得的是0分, 我也跟别人试过一些数据,但是测的基本上不是一串F就是一串其他的,反倒是帮人找出来了一个错误,但是自己的错误还是没有找到,曾经还一度认为是我的栈开的不够大,所以导致的最后数据溢出,不能精确表示。后来请教了c语言吧的女神 幽罹焰我才发现了我的代码错误地方。错误地方就在于偷懒的  printf("%o", stack[i]);  因为我是偷懒的加和, 为此丢失了许多该有的前导0。


 

而1001转化之后的正确结果应该是10001。

为此为了修正这个错误,我最后还是转化为了字符串, 看当前的数字是否凑够了 4位,为此有了如下代码。

#include<iostream>#include<cstring>#include<cstdio>using namespace std;int stack[40000];void transform(string str, int length){    char buff[4];     int top = -1;    for(int i = length - 1; i >= 0; i -= 3)    {        int sum = 0;        for(int j = 0; j < 3 && i - j >= 0; j++)        {            int temp = str[i - j] >= '0' && str[i - j] <= '9' ? str[i - j] - '0' : str[i - j] - 'A' + 10;            sum += (temp << (4 * j));        }        stack[++top] = sum;    }    while( stack[top] == 0)    {    top--;    }    for(int i = top; i >= 0; i--)    {        printf("%04o", stack[i]);    }    cout<<endl;}int main(){string *str;int n;cin>>n;str = new string[n];for(int i = 0; i < n; i++){cin>>str[i];}for(int i = 0; i < n; i++){transform(str[i], str[i].size());}return 0;}


 

这样就能使答案正确输出。

 

0 0