What is wrong with my toBinary() method? It looks right to me when I run the code.
package en.codegym.task.pro.task09.task0908;
/*
Binary to hexadecimal converter
*/
public class Solution {
private static final String HEX = "0123456789abcdef";
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) {
//write your code here
if (binaryNumber == "" || binaryNumber == null) return "";
String testNumber = binaryNumber;
while (testNumber.length() % 4 != 0) {
testNumber = '0' + testNumber;
}
int binaryToDecimal = toDecimal(testNumber);
String decimalToHex = toHex(binaryToDecimal);
return decimalToHex;
}
public static String toBinary(String hexNumber) {
//write your code here
if (hexNumber == "" || hexNumber == null) return "";
for (int i = 0; i < hexNumber.length(); i++) {
Character letter = hexNumber.charAt(i);
if (HEX.indexOf(letter) == -1) return "";
}
int decimalNumber = hexToDecimal(hexNumber);
String binaryNumber = decimalToBinary(decimalNumber);
return binaryNumber;
}
public static int toDecimal(String binaryNumber) {
//write your code here
int decimalNumber = 0;
if (binaryNumber == "" || binaryNumber == null) return 0;
for (int i = 0; i < binaryNumber.length(); i++) {
char lastChar = binaryNumber.toCharArray()[binaryNumber.length()-1-i];
int lastDigit = Character.getNumericValue(lastChar);
decimalNumber = decimalNumber + lastDigit * (int)Math.pow(2.0, i);
}
return decimalNumber;
}
public static String toHex(int decimalNumber) {
//write your code here
String hexNumber = "";
if (decimalNumber <= 0) return "";
while (decimalNumber != 0) {
int idx = decimalNumber % 16;
char digit = HEX.charAt(idx);
hexNumber = digit + hexNumber;
decimalNumber = decimalNumber / 16;
}
return hexNumber;
}
public static int hexToDecimal(String hexNumber) {
//write your code here
int decimalNumber = 0;
if (hexNumber == "" || hexNumber == null) return 0;
for (int i = 0; i < hexNumber.length(); i++) {
char letter = hexNumber.charAt(i);
int idx = HEX.indexOf(letter);
decimalNumber = 16 * decimalNumber +idx;
}
return decimalNumber;
}
public static String decimalToBinary(int decimalNumber) {
//write your code here
String binaryNumber = "";
if (decimalNumber <= 0) return "";
while(decimalNumber != 0) {
binaryNumber = decimalNumber % 2 + binaryNumber;
decimalNumber /= 2;
}
return binaryNumber;
}
}