Binary to decimal in java using only recursion (no loops) - java

I can not seem to get my method to convert the binary number to a decimal correctly. I believe i am really close and in fact i want to use a string to hold the binary number to hold it and then re-write my method to just use a .length to get the size but i do not know how to actually do that. Could someone help me figure out how i'd rewrite the code using a string to hold the binary value and then obtain the decimal value using only recursion and no loops?
This is my full code right now and i won't get get rid of asking for the size of the binary and use a string to figure it out myself. Please help :)
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
int input;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer: ");
input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer and size : ");
input = scan.nextInt();
size = scan.nextInt();
System.out.println(binaryToDecimal(input, size));
}
public static void convert(int num) {
if (num > 0) {
convert(num / 2);
System.out.print(num % 2 + " ");
}
}
public static int binaryToDecimal(int binary, int size) {
if (binary == 0) {
return 0;
}
return binary % 10
* (int) Math.pow(2, size) + binaryToDecimal((int) binary / 10, size - 1);
}
}

Here is an improved version
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer : ");
int input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer : ");
String binInput = scan.next();
System.out.println(binaryToDecimal(binInput));
}
public static void convert(int num) {
if (num>0) {
convert(num/2);
System.out.print(num%2 + " ");
}
}
public static int binaryToDecimal(String binInput){
int len = binInput.length();
if (len == 0) return 0;
String now = binInput.substring(0,1);
String later = binInput.substring(1);
return Integer.parseInt(now) * (int)Math.pow(2, len-1) + binaryToDecimal(later);
}
}

Don't parse binary in reverse order.
Here by calling binaryToDecimal(int) it will return decimal number.
public static int binaryToDecimal(int binary) {
return binaryToDecimal(binary, 0);
}
public static int binaryToDecimal(int binary, int k) {
if (binary == 0) {
return 0;
}
return (int) (binary % 10 * Math.pow(2, k) + binaryToDecimal(binary / 10, k + 1));
}
If you are coding just to convert numbers (not for practice). Then better approach would be to use Integer.parseInt(String, 2). Here you will have to pass binary number in the form of String.

If you are looking to do this using a String to hold the binary representation, you could use the following:
public static int binaryToDecimal(String binaryString) {
int size = binaryString.length();
if (size == 1) {
return Integer.parseInt(binaryString);
} else {
return binaryToDecimal(binaryString.substring(1, size)) + Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1);
}
}
How this works, is with the following logic. If, the number you send it is just 1 character long, or you get to the end of your recursive work, you will return just that number. So for example, 1 in binary is 1 in decimal, so it would return 1. That is what
if (size == 1) {
return Integer.parseInt(binaryString);
}
Does. The second (and more important part) can be broken up into 2 sections. binaryString.substring(1, size) and Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1). The call made in the return statement to
binaryString.substring(1, size)
Is made to pass all but the first number of the binary number back into the function for calculation. So for example, if you had 11001, on the first loop it would chop the first 1 off and call the function again with 1001. The second part, is adding to the total value whatever the value is of the position number at the head of the binary representation.
Integer.parseInt(binaryString.substring(0, 1))
Gets the first number in the current string, and
* (int) Math.pow(2, size - 1)
is saying Multiple that by 2 to the power of x, where x is the position that the number is in. So again with our example of 11001, the first number 1 is in position 4 in the binary representation, so it is adding 1 * 2^4 to the running total.
If you need a method to test this, I verified it working with a simple main method:
public static void main(String args[]) {
String binValue = "11001";
System.out.println(binaryToDecimal(binValue));
}
Hopefully this makes sense to you. Feel free to ask questions if you need more help.

Here is the clean and concise recursive algorithm; however, you'll need to keep track of some global variable for power, and I have defined it as a static member.
static int pow = 0;
public static int binaryToDecimal(int binary) {
if (binary <= 1) {
int tmp = pow;
pow = 0;
return binary * (int) Math.pow(2, tmp);
} else {
return ((binary % 10) * (int) Math.pow(2, pow++)) + binaryToDecimal(binary / 10);
}
}
Note: the reason, why I introduce pow, is that static field needs to be reset.

Just did the necessary changes in your code.
In this way, you would not require the size input from the user.
And,both the conversions of decimal to binary and binary to decimal would be succesfully done.
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
int input;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer: ");
input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer : ");
input = scan.nextInt();
System.out.println(binaryToDecimal(input));
}
public static void convert(int num) {
if (num > 0) {
convert(num / 2);
System.out.print(num % 2 + " ");
}
return -1;
}
public static int binaryToDecimal(int binary) {
if(binary==0)
{
return 0;
}
else
{
String n=Integer.toString(binary);
int size=(n.length())-1;
int k=(binary%10)*(int)(Math.pow(2,size));
return k + binaryToDecimal(((int)binary/10));
}
}
}

Related

how to convert decimal value in to a Fraction value?

excepted output : 1/4,1/2,3/4,1,5/4,3/2
but my output is coming as in the decimal form . Please help how to print in the form of fraction only.
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(sum+" ");
}
}}
take input in form of string so it will take input in required format and split it by "/" i.e someString.spit("/").
after that make one for loop and take two number and in two different variable store it.
and then take division for both and print it by using "/" in between them.
public class NewClass {
public static void main(String[] args) {
System.out.println(convertype(0.75));
}
public static String convertype(double decimal){
int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits
BigInteger numerator = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75
BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint))); // 10^2 is your denominator
int gcd = numerator.gcd(denominator).intValue(); // calculate the greatest common divisor of numerator and denominator
if (gcd > 1 ){ // gcd(75,100) = 25
return String.valueOf(numerator.intValue()/gcd) +" / " + String.valueOf(denominator.intValue()/gcd); // return 75/25 / 100/25 = 3/4
}
else{
return String.valueOf(numerator) +" / " + String.valueOf(denominator); // if gcd = 1 which means nothing to simplify just return numerator / denominator
}
}
}
Wrote a method where you can convert double numbers to fraction. Use this to convert it and print as below,
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(toFraction(sum)+" ");
}
}
static String toFraction(double x) {
int w = (int) x;
int n = (int) (x * 64) % 64;
int a = n & -n;
return n == 0 ? w+"" : (w * (64 / a) + (n / a)) + "/" + 64 / a;
}
}

Java - Recursion Program - way to convert an inputted base to base 10 on a given number

I am given a non-recursive method, that I need to modify to make recursive.
This is what I have so far:
public class BaseN {
public static final int BASEN_ERRNO = -1;
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
System.out.print("enter number followed by base (e.g. 237 8): ");
int number = input.nextInt();
int base = input.nextInt();
BigInteger answer = basen(number, base);
System.out.println(number + " base-" + base + " = " + answer);
}
static BigInteger basen(int number, int base ) {
List<Integer> remainder = new ArrayList<>();
int count = 0;
String result = "";
while( number != 0 ) {
remainder.add( count, number % base != 0 ? number % base : 0 );
number /= base;
try {
result += remainder.get( count );
} catch( NumberFormatException e ) {
e.printStackTrace();
}
}
return new BigInteger( new StringBuffer( result ).reverse().toString() );
}
}
It's converting it to base 10 then the given base. I need it to convert to the given base first then base 10.
UPDATE:
I changed around Caetano's code a bit and think I am closer.
static String basen(int number, int base) {
String result = String.valueOf(number % base);
int resultC;
String resultD;
int newNumber = number / base;
if (newNumber != 0)
result += basen(newNumber, base);
if (newNumber == 0)
resultC = Integer.parseInt(result);
resultD = Integer.toString(resultC);
return resultD;
Now when I compile it it gives me an error it says:
BaseN.java:49: error: variable resultC might not have been initialized
resultD = Integer.toString(resultC);
Am I on the right track here? Any help is appreciated
Its hard to tell what you are asking for.
I can only assume that you want to convert from a given base to base 10. The way that you would do this is explained in this page here: MathBits introduction to base 10.
The way explained in this is simple. For each digit in the number you get the base to the power of the position of the digit(reversed) and multiply that by whatever the digit is. Then add all the results. So 237 in base 8 would be
(8^2 * 2) + (8^1 * 3) + (8^0 * 7) = 159
Now you will run in to a problem when you do this with bases higher then 10 since the general notation for digits above 9 is alphabetical letters. However you could get around this by having a list of values such as [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F] and compare the digits with this list and get the index of the location of that digit as the number.
I hope this is what you were asking for.
Now then this is code that does what you want it to do. Get a number in a given base and convert it to base 10. However I don't see why you need to use a recursive method for this. If this is some kind of school task or project then please tell us the details because I don't personally see a reason to use recursion. However the fact that your question asks us to modify the code up top to make it recursive then it makes much more sense. Since that code can be edited to be as such.
public static final int BASEN_ERRNO = -1;
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
System.out.print("enter number followed by base (e.g. 237 8): ");
String number = input.next();
int base = input.nextInt();
int answer = basen(number, base);
System.out.println(number + " base-" + base + " = " + answer);
}
private static int basen(String number, int base ) {
int result = 0;
for(int i = 0; i < number.length(); i++) {
int num = Integer.parseInt(number.substring(i, i + 1));
result += Math.pow(base, number.length() - i - 1) * num;
}
return result;
}
However what I think that you want is actually this which shows recursion but instead of converting from base given to base 10 it converts from base 10 to base given. Which is exactly what the code you showed does but uses recursion. Which means '512 6' will output '2212'
public static final int BASEN_ERRNO = -1;
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
System.out.print("enter number followed by base (e.g. 237 8): ");
int number = input.nextInt();
int base = input.nextInt();
String answer = new StringBuffer(basen(number, base)).reverse().toString();
System.out.println(number + " base-" + base + " = " + answer);
}
static String basen(int number, int base) {
String result = String.valueOf(number % base);
int newNumber = number / base;
if (newNumber != 0)
result += basen(newNumber, base);
return result;
}
I figured out a way to do it recursively. Thank you everyone who provided help. I ended up using Math.pow on the base and put the length of the number -1 for how it would be exponentially increased. Math.pow puts the result in double format so I just converted it back to an int. My professor gave me 100% for this answer, so I'd imagine it would work for others too.
public static int basen(int number, int base) {
String numberStr;
int numberL;
char one;
String remainder;
int oneInt;
int remainderInt;
double power;
int powerInt;
numberStr = Integer.toString(number);
numberL = numberStr.length();
if(numberL > 1){
one = numberStr.charAt(0);
remainder = numberStr.substring(1);
oneInt = Character.getNumericValue(one);
remainderInt = Integer.parseInt(remainder);
power = Math.pow(base, (numberL - 1));
powerInt = (int)power;
return ((oneInt * powerInt) + (basen(remainderInt, base)));
}
else{
return number;
}
}

Converting decimal to binary (Java)

I'm trying to convert decimal to binary but some how when I convert 128 binary the output gives me 11111110, I tried to fix the calculation but still end up with the same output.
import java.lang.*;
public class HA7BinaryErr {
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
int number = 0;
int factorOfTwo = 0;
// get number to convert from user
do {
System.out.println("Enter the number to convert (0-255): ");
number = input.nextInt();
} while (number < 0 || number > 255);
System.out.println("The number " + number + " converted to binary is : ");
// convert to binary by successively dividing by larger factors of 2
for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo *= 2) {
if (number / factorOfTwo >= 1) {
System.out.print("1");
number -= factorOfTwo;
} else
System.out.print("0");
}
} // end of main
}// end of class
You have a problem that you are writing the number backwards. You need to start with the highest bit first
for (int powerOfTwo = 128; powerOfTwo > 0; powerOfTwo /= 2) {
When you are writing in decimal you start with the highest power e.g. 1234 is 1 * 1000 + 2 * 100 + 3 * 10 + 4 * 1
You could take the easy way out and use:
Integer.toBinaryString(int i) then print the string to the console.
Check it out here.
public class DCTB {
public void convertor(int n)
{
for(int i=0;i<10;i++)
{
int arr=(int) (n%2);
n=n/2;
System.out.println(Integer.toString(arr));
}
}
public static void main(String args[])
{
DCTB obj=new DCTB();
obj.convertor(10);
}
}

Converting From Decimal to Binary In Java

So I have code that will convert a decimal number to binary. I use a recursive algorithm for it, however I cannot seem to get it to do what I want. Here is the code:
import java.util.*;
public class binaryAddition {
public static int toBinary(int a){
int bin = 0;
int remainder = 0;
if(a >= 1){
toBinary(a/2);
bin = (a%2);
}
return bin;
}
public static void main(String[] args){
System.out.println(toBinary(3));
System.out.print(toBinary(3));
}
}
So I want to to return the binary solution so that I can save it as a variable in my main method. However, my current output would only give me that last digit of the binary number. I used the number 3 just as a test case and I get 1 as an output for both print and println methods. Why is that, and how can I fix it?
Many Thanks!
For a start, you might want to have toBinary return a String, not an int. Then you must use the result of it when you recurse. So you might write, inside your if,
bin = toBinary(a / 2) + (a % 2);
assuming, of course, that toBinary returns String.
If you don't do this, then you're just throwing away the result of your calculation.
The code is discarding the results of the recursive calls.
Do something with the result of toBinary in the method.
Just Do it Like i have Done .
public static void main(String[] args)
{
int n, count = 0, a;
String x = "";
Scanner s = new Scanner(System.in);
System.out.print("Enter any decimal number:");
n = s.nextInt();
while(n > 0)
{
a = n % 2;
if(a == 1)
{
count++;
}
x = x + "" + a;
n = n / 2;
}
System.out.println("Binary number:"+x);
System.out.println("No. of 1s:"+count);
}

Using Recursion to reverse an integer without the use of strings

I have been trying this for some time now but could not get it to work. I am trying to have a method to reverse an integer without the use of strings or arrays. For example, 123 should reverse to 321 in integer form.
My first attempt:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
int tempRev = RevDigs(input/10);
if(tempRev >= 10)
reverse = input%10 * (int)Math.pow(tempRev/10, 2) + tempRev;
if(tempRev <10 && tempRev >0)
reverse = input%10*10 + tempRev;
if(tempRev == 0)
reverse = input%10;
return reverse;
}//======================
I also tried to use this, but it seems to mess up middle digits:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
if(RevDigs(input/10) == 0)
reverse = input % 10;
else
{
if(RevDigs(input/10) < 10)
reverse = (input % 10) *10 + RevDigs(input/10);
else
reverse = (input % 10)* 10 * (RevDigs(input/10)/10 + 1) + RevDigs(input/10);
}
return reverse;
}
I have tried looking at some examples on the site, however I could not get them to work properly. To further clarify, I cannot use a String, or array for this project, and must use recursion. Could someone please help me to fix the problem. Thank you.
How about using two methods
public static long reverse(long n) {
return reverse(n, 0);
}
private static long reverse(long n, long m) {
return n == 0 ? m : reverse(n / 10, m * 10 + n % 10);
}
public static void main(String... ignored) {
System.out.println(reverse(123456789));
}
prints
987654321
What about:
public int RevDigs(int input) {
if(input < 10) {
return input;
}
else {
return (input % 10) * (int) Math.pow(10, (int) Math.log10(input)) + RevDigs(input/10);
/* here we:
- take last digit of input
- multiply by an adequate power of ten
(to set this digit in a "right place" of result)
- add input without last digit, reversed
*/
}
}
This assumes input >= 0, of course.
The key to using recursion is to notice that the problem you're trying to solve contains a smaller instance of the same problem. Here, if you're trying to reverse the number 13579, you might notice that you can make it a smaller problem by reversing 3579 (the same problem but smaller), multiplying the result by 10, and adding 1 (the digit you took off). Or you could reverse the number 1357 (recursively), giving 7531, then add 9 * (some power of 10) to the result. The first tricky thing is that you have to know when to stop (when you have a 1-digit number). The second thing is that for this problem, you'll have to figure out how many digits the number is so that you can get the power of 10 right. You could use Math.log10, or you could use a loop where you start with 1 and multiply by 10 until it's greater than your number.
package Test;
public class Recursive {
int i=1;
int multiple=10;
int reqnum=0;
public int recur(int no){
int reminder, revno;
if (no/10==0) {reqnum=no;
System.out.println(" reqnum "+reqnum);
return reqnum;}
reminder=no%10;
//multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
i++;
no=recur(no/10);
reqnum=reqnum+(reminder*multiple);
multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
return reqnum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=123456789;
Recursive r= new Recursive();
System.out.println(r.recur(num));
}
}
Try this:
import java.io.*;
public class ReversalOfNumber {
public static int sum =0;
public static void main(String args []) throws IOException
{
System.out.println("Enter a number to get Reverse & Press Enter Button");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
int number = Integer.parseInt(input);
int revNumber = reverse(number);
System.out.println("Reverse of "+number+" is: "+revNumber);
}
public static int reverse(int n)
{
int unit;
if (n>0)
{
unit = n % 10;
sum= (sum*10)+unit;
n=n/10;
reverse(n);
}
return sum;
}
}

Categories