标签:
#include<stdio.h> #include<string.h> #include<string> #include<math.h> #include<algorithm> #define LL long long #define PI atan(1.0)*4 #define DD doublea #define MAX 100100 #define mod 10007 using namespace std; char a[MAX]; int p[MAX*10]; int main() { int n,m,j,i,len,sum; scanf("%d",&n); while(n--) { scanf("%s",&a); char s[MAX*10]=""; len=strlen(a); for(i=0;i<len;i++) //转化为二进制 { switch(a[i]) { case ‘0‘:strcat(s,"0000");break; case ‘1‘:strcat(s,"0001");break; case ‘2‘:strcat(s,"0010");break; case ‘3‘:strcat(s,"0011");break; case ‘4‘:strcat(s,"0100");break; case ‘5‘:strcat(s,"0101");break; case ‘6‘:strcat(s,"0110");break; case ‘7‘:strcat(s,"0111");break; case ‘8‘:strcat(s,"1000");break; case ‘9‘:strcat(s,"1001");break; case ‘A‘:strcat(s,"1010");break; case ‘B‘:strcat(s,"1011");break; case ‘C‘:strcat(s,"1100");break; case ‘D‘:strcat(s,"1101");break; case ‘E‘:strcat(s,"1110");break; case ‘F‘:strcat(s,"1111");break; default:break; } } //puts(s); strrev(s); int len1=strlen(s); if(len1%3==1) //因为二进制转八进制,是有三位二进制变为一位八进制 { //所以要补全,在前边补0使长度能整除3 strcat(s,"00"); len1+=2; } else if(len1%3==2) { strcat(s,"0"); len1+=1; } int op=1; for(i=0;i<len1-2;i+=3) //二进制转八进制 { p[op++]=(s[i]-‘0‘)*1+(s[i+1]-‘0‘)*2+(s[i+2]-‘0‘)*4; } int flag=1; for(i=op;i>0;i--) { if(p[i]!=0) flag=0; if(p[i]==0&&flag) continue; printf("%d",p[i]); } printf("\n"); } return 0; }
AC代码:
#include<stdio.h> #include<string.h> #include<string> #include<math.h> #include<algorithm> #define LL long long #define PI atan(1.0)*4 #define DD doublea #define MAX 100100 #define mod 10007 using namespace std; int p[MAX*10]; int main() { int n,m,j,i,len,sum; scanf("%d",&n); while(n--) { string a,s; a.resize(MAX); //需要预先分配空间 scanf("%s",&a[0]); s=""; len=a.length();//字符串长度 for(i=0;i<len;i++) { switch(a[i]) { case ‘0‘:s+="0000";break; case ‘1‘:s+="0001";break; case ‘2‘:s+="0010";break; case ‘3‘:s+="0011";break; case ‘4‘:s+="0100";break; case ‘5‘:s+="0101";break; case ‘6‘:s+="0110";break; case ‘7‘:s+="0111";break; case ‘8‘:s+="1000";break; case ‘9‘:s+="1001";break; case ‘A‘:s+="1010";break; case ‘B‘:s+="1011";break; case ‘C‘:s+="1100";break; case ‘D‘:s+="1101";break; case ‘E‘:s+="1110";break; case ‘F‘:s+="1111";break; default:break; } } //puts(s); //strrev(s); int len1=s.length(); if(len1%3==1) { s="00"+s; //00+s是将00加在字符串前 s+00是将00加在字符串后 len1+=2; } else if(len1%3==2) { s="0"+s; len1+=1; } int op=1; for(i=0;i<len1-2;i+=3) { p[op++]=(s[i]-‘0‘)*4+(s[i+1]-‘0‘)*2+(s[i+2]-‘0‘)*1; } int flag=1; for(i=0;i<op;i++) { if(p[i]!=0) flag=0; if(p[i]==0&&flag) continue; printf("%d",p[i]); } printf("\n"); } return 0; }
标签:
原文地址:http://www.cnblogs.com/tonghao/p/5131319.html