Basic practice hexadecimal decimal time limit: 1.0s memory Limit: 512.0MB problem description Enter a positive hexadecimal number string that is no more than 8 digits from the keyboard and convert it to a positive decimal number after the output.
Note: The 10~15 in the hexadecimal number are expressed in uppercase letters A, B, C, D, E, and F, respectively. Sample input FFFF sample output 65535 analysis of the problem, the 16 conversion to decimal, where the hexadecimal string does not exceed 8 bits, first of all think of calling the system method implementation. Directly using the integer.valueof (HEXSTR). ToString () method, the test output error exceeded the integer type length range and was therefore replaced by long.valueof (HEXSTR). ToString (), Test passed.
Import Java.util.Scanner;
public class main{public
static void transform () {
Scanner sc = new Scanner (system.in);
String Arry = "";
String number = Sc.next ();
if (Number.length () <= 8) {
Arry = long.valueof (number,). toString ();
System.out.println (Arry);
}
public static void Main (string[] args) {
transform ();
}
}
Then I wrote the implementation algorithm: first convert 16 to binary, one hex to 4-bit binary. Then convert binary to decimal, from right to left, encounter 1 bit, tired plus 2 n-1, test pass.
Import Java.util.Scanner; public class main{public static void Converthexintodecimal (char[] Arryhex, String hexstr) {StringBuilder =
New StringBuilder ();
int len = Hexstr.length ();
Long Count = 1;
Long decimal = 0;
String binarystr = "";
Arryhex = Hexstr.tochararray (); for (int i = 0; i < len; i++) {//convert Hex to Binary switch (arryhex[i)) {case ' 0 ': Binarystb.append ("0
000 ");
Break
Case ' 1 ': Binarystb.append ("0001");
Break
Case ' 2 ': Binarystb.append ("0010");
Break
Case ' 3 ': Binarystb.append ("0011");
Break
Case ' 4 ': Binarystb.append ("0100");
Break
Case ' 5 ': Binarystb.append ("0101");
Break
Case ' 6 ': Binarystb.append ("0110");
Break
Case ' 7 ': Binarystb.append ("0111");
Break
Case ' 8 ': Binarystb.append ("1000");
Break
Case ' 9 ': Binarystb.append ("1001");
Break
Case ' A ': Binarystb.append ("1010");
Break Case ' B ': BinaRystb.append ("1011");
Break
Case ' C ': Binarystb.append ("1100");
Break
Case ' D ': Binarystb.append ("1101");
Break
Case ' E ': Binarystb.append ("1110");
Break
Case ' F ': binarystb.append ("1111");
Break
Default:break;
} binarystr = Binarystb.tostring ();
Len = Binarystr.length ();
for (int i = len-1 i >= 0; i--) {if (Binarystr.charat (i) = = ' 1 ') {decimal = decimal + count;
Count = Count * 2;
} System.out.println (decimal);
public static void Main (string[] args) {Scanner sc = new Scanner (system.in);
char [] Arryhex = new Char[8];
String hexstr = Sc.next ();
Converthexintodecimal (ARRYHEX,HEXSTR);
}
}