1. 程式人生 > >藍橋杯-- 基礎練習 十六進位制轉八進位制(大數操作)

藍橋杯-- 基礎練習 十六進位制轉八進位制(大數操作)

  基礎練習 十六進位制轉八進位制   時間限制:1.0s   記憶體限制:512.0MB 問題描述   給定n個十六進位制正整數,輸出它們對應的八進位制數。 輸入格式   輸入的第一行為一個正整數n (1<=n<=10)。
  接下來n行,每行一個由0~9、大寫字母A~F組成的字串,表示要轉換的十六進位制正整數,每個十六進位制數長度不超過100000。 輸出格式   輸出n行,每行為輸入對應的八進位制正整數。 注意   輸入的十六進位制數不會有前導0,比如012A。
  輸出的八進位制數也不能有前導0。 樣例輸入 2
39
123ABC 樣例輸出 71
4435274 提示   先將十六進位制數轉換成某進位制數,再由某進位制數轉換成八進位制。

C++用時23ms

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
bool b[400100];
char s[100001];
int a[400001];
int main()
{
    int len,n,i,t,p;
    scanf("%d",&n);
    while (n--)
    {
        memset(s,'0',sizeof(s));
        memset(b,0,sizeof(b));
        scanf("%s",s);
        len=strlen(s);
        t=4*len;
        s[len]='0';
        for (i=0;i<len;i++)
        {
            if (s[i]=='0') {b[t]=0;b[t-1]=0;b[t-2]=0;b[t-3]=0;}
            if (s[i]=='1') {b[t]=0;b[t-1]=0;b[t-2]=0;b[t-3]=1;}
            if (s[i]=='2') {b[t]=0;b[t-1]=0;b[t-2]=1;b[t-3]=0;}
            if (s[i]=='3') {b[t]=0;b[t-1]=0;b[t-2]=1;b[t-3]=1;}
            if (s[i]=='4') {b[t]=0;b[t-1]=1;b[t-2]=0;b[t-3]=0;}
            if (s[i]=='5') {b[t]=0;b[t-1]=1;b[t-2]=0;b[t-3]=1;}
            if (s[i]=='6') {b[t]=0;b[t-1]=1;b[t-2]=1;b[t-3]=0;}
            if (s[i]=='7') {b[t]=0;b[t-1]=1;b[t-2]=1;b[t-3]=1;}
            if (s[i]=='8') {b[t]=1;b[t-1]=0;b[t-2]=0;b[t-3]=0;}
            if (s[i]=='9') {b[t]=1;b[t-1]=0;b[t-2]=0;b[t-3]=1;}
            if (s[i]=='A') {b[t]=1;b[t-1]=0;b[t-2]=1;b[t-3]=0;}
            if (s[i]=='B') {b[t]=1;b[t-1]=0;b[t-2]=1;b[t-3]=1;}
            if (s[i]=='C') {b[t]=1;b[t-1]=1;b[t-2]=0;b[t-3]=0;}
            if (s[i]=='D') {b[t]=1;b[t-1]=1;b[t-2]=0;b[t-3]=1;}
            if (s[i]=='E') {b[t]=1;b[t-1]=1;b[t-2]=1;b[t-3]=0;}
            if (s[i]=='F') {b[t]=1;b[t-1]=1;b[t-2]=1;b[t-3]=1;}
            t-=4;
        }
        t=len*4;
        while (!b[t]) t--;
        p=0;
        for (i=1;i<=t;i+=3)
        {
            if (!b[i] && !b[i+1] && !b[i+2]) a[++p]=0;
            if (b[i] && !b[i+1] && !b[i+2]) a[++p]=1;
            if (!b[i] && b[i+1] && !b[i+2]) a[++p]=2;
            if (b[i] && b[i+1] && !b[i+2]) a[++p]=3;
            if (!b[i] && !b[i+1] && b[i+2]) a[++p]=4;
            if (b[i] && !b[i+1] && b[i+2]) a[++p]=5;
            if (!b[i] && b[i+1] && b[i+2]) a[++p]=6;
            if (b[i] && b[i+1] && b[i+2]) a[++p]=7;
        }
        for (i=p;i>=1;i--) printf("%d",a[i]);
        printf("\n");
    }
    return 0;
}


JAVA超時的說。。。。。。

import java.io.*;
import java.math.BigInteger;

public class Main {

	public static void main(String[] args) throws IOException {
		
		BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
		String s;
	   while((s=sc.readLine())!=null){//超時=======!
		   
		   BigInteger d  = new BigInteger(s,16);
		   System.out.println(String.format("%o", d));
	   }
	}
}