hexToBinary method run successfully and also i test some other number, but failed the task test. why? please help me!
package en.codegym.task.pro.task09.task0908;
/*
Binary to hexadecimal converter
*/
public class Solution {
public static void main(String[] args) {
String binaryNumber = "100111010000";
System.out.println("Binary number " + binaryNumber + " is equal to hexadecimal number " + toHex(binaryNumber));
String hexNumber = "9d0";
System.out.println("Hexadecimal number " + hexNumber + " is equal to binary number " + toBinary(hexNumber));
}
public static String toHex(String binaryNumber) {
if(binaryNumber != null){
String hex = "0123456789abcdef";
String hexN = "";
int tempN = binaryNumber.length() % 4;
if (tempN != 0) {
for (int i = 0; i < 4 - tempN; i++) {
binaryNumber = "0" + binaryNumber;
}
}
for (int i = 0; i < binaryNumber.length(); i += 4) {
String subBin = binaryNumber.substring(i, i + 4);
//System.out.println(subBin.toString());
int decN = 0;
for (int j = 0; j < subBin.length(); j++) {
if ((subBin.charAt(j)) == '1') {
decN = (int) (decN + Math.pow(2, subBin.length() - 1 - j));
}
//System.out.println(decN);
}
hexN = hexN + String.valueOf(hex.charAt(decN));
}
return hexN;
}else {
return "";
}
}
public static String toBinary(String hexNumber) {
String HEX = "0123456789abcdef";
String hex = "";
if (hexNumber == null) {
return "";
}else {
for (int i = 0; i < hexNumber.length(); i++) {
int number = HEX.indexOf(hexNumber.charAt(i));
String bin = "";
if (0 <= number && number < 15) {
for(int j =0; j<4; j++){
if(number != 0){
bin = number % 2 + bin;
number = number / 2;
}else{
bin = "0" + bin;
}
}
}
hex = hex + bin;
}
}
return hex;
}
}