Decimal To binary Recursive conversion java?
My conversion is wrong there is an additional zero i would be very grateful if somebody could help me figure out what is wrong with my code i know it would be easier having one method for this but i want to use both a private method that takes a string buffer and an int and a public method that takes an int . code is below
Code :
public class DecToBin
{
public static void main (String [] args)
{
System.out.println (" the value of 10 in binary is " + decimalToBinary (10));
System.out.println (" the value of 1 in binary is " + decimalToBinary (1));
System.out.println (" the value of 2 in binary is " + decimalToBinary (2));
System.out.println (" the value of 5 in binary is " + decimalToBinary (5));
System.out.println (" the value of -5 in binary is " + decimalToBinary (-5));
}
private static String decimalToBinary(int decimal, StringBuffer buffer)
{
buffer.append(decimal % 2);
decimal /= 2;
if (decimal == 0) return buffer.reverse().toString();
else return decimalToBinary(decimal, buffer);
}
public static String decimalToBinary (int decimal)
{
StringBuffer buffer = new StringBuffer ();
if (decimal < 0)
return " - " + decimalToBinary (decimal* -1);
else return decimalToBinary (decimal, buffer.append(decimal %2));
}
}
Re: Decimal To binary Recursive conversion java?
Coz of your buffer.append(decimal%2) statement in
Code :
public static String decimalToBinary (int decimal)
{
StringBuffer buffer = new StringBuffer ();
if (decimal < 0)
return " - " + decimalToBinary (decimal* -1);
else return decimalToBinary (decimal, buffer.append(decimal %2));
}
It's also appending the zero in buffer this time.