Questions basic exercises from hexadecimal octal

Questions basic exercises from hexadecimal octal

Resource constraints

Time limit: 1.0s Memory Limit: 512.0MB

Problem Description

  Given a positive integer n hexadecimal, octal output thereof corresponds.

Input Format

  The first act input a positive integer n (1 <= n <= 10).   Next n lines, each line of a character string from 0 to 9, capital letters A ~ F composition indicates hexadecimal to convert a positive integer, each hexadecimal number length does not exceed 100,000.

Output Format

  N output lines, each act input octal positive integer corresponding.

  [Note]   enter the hexadecimal number does not have leading 0, such as 012A.   Octal number also can not have a leading zero.

Sample input

  2   39   123ABC

Sample Output

  71   4435274

【prompt】

  First convert a hexadecimal number to a decimal number, and then converted by a binary number to octal.

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 / 8;
if (k == 0) {
ansStr[pos++] = (char)( res + Integer.valueOf('0'));
res = 0;
}
}
if (res != 0)
ansStr[pos++] = (char)( res + Integer.valueOf('0'));
if(ansStr[pos-1] == '0')
pos--;
for(int i=pos-1;i>=0;i--)
System.out.print(ansStr[i]);
System.out.println("");
}
}
}

to sum up

Thinking

Here mainly on account of the position to write, rather than analog

According to a hex binary turn four, three binary transfer an octal, then 1 digit hexadecimal number is converted to an octal, but more than one, this an additional consideration again on the line.

We can still put it to the res, so in the first two hexadecimal numbers, we can consider go.

Then three hex will be more of a octal out, think about it is not enough three zeros.

The general idea is this.

note

+ String the time complexity is O (N), it can not be used where the String +

Guess you like

Origin www.cnblogs.com/acm-cyz/p/12601011.html