This can be done this way as well. But I think this type of problem in which you can break big problem into same type of small problem, can be done easily and very effectively using recursion like this
public static int HexToDec(String number ) { if ( number.length() == 1 ) { return Integer.parseInt(number,16); } String digit = number.substring( number.length()-1, number.length() );
2 comments:
We can have a lookup map. A simple HashMap.
Hashmap h = new HashMap()
In which we can put the letters and corresponding multiplier.
h.put("A",10)
h.put("B",11)
Then we can iterate over string and use this map and the position of character to calculate the decimal value
This can be done this way as well. But I think this type of problem in which you can break big problem into same type of small problem, can be done easily and very effectively using recursion like this
public static int HexToDec(String number )
{
if ( number.length() == 1 )
{
return Integer.parseInt(number,16);
}
String digit = number.substring( number.length()-1, number.length() );
System.out.println("digit = " + digit );
return Integer.parseInt(digit,16) + 16*HexToDec(number.substring(0, number.length()-1) );
}
Similary, can you convert decimal to binary using recursion?
Post a Comment