資源限制
時間限制:1.0s 內存限制:512.0MB
問題描述
給定n個十六進制正整數,輸出它們對應的八進制數。
輸入格式
輸入的第一行為一個正整數n (1<=n<=10)。 接下來n行,每行一個由0~9、大寫字母A~F組成的字符串,表示要轉換的十六進制正整數,每個十六進制數長度不超過100000。
輸出格式
輸出n行,每行為輸入對應的八進制正整數。
【注意】 輸入的十六進制數不會有前導0,比如012A。 輸出的八進制數也不能有前導0。
樣例輸入
2 39 123ABC
樣例輸出
71 4435274
【提示】
先將十六進制數轉換成某進制數,再由某進制數轉換成八進制。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n;
n = s.nextInt();
while (n > 0) {
n--;
String str;
char ansStr[] = new char[200010];
str = s.next();
int l = str.length();
int res = 0, k = 0, pos = 0;
for (int i = l - 1; i >= 0; i--) {
int temp = Integer.valueOf(str.charAt(i));
temp = temp>=65&&temp<=90 ? temp-65 + 10 : temp-Integer.valueOf('0') ;
int ttemp = 1;
if(k == 1)
ttemp = 2;
if(k == 2)
ttemp = 4;
res = ttemp * temp+ res;
ansStr[pos++] = (char)(res % 8+Integer.valueOf('0'));
k = (k + 1) % 3;
res = res