Advertisement
NicholasCSW

Binary Recursion

Apr 30th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1.  
  2. /**
  3.  * Simple recursive method to convert ints to their binary equivalent.
  4.  *
  5.  * @author Ulizio
  6.  * @version 1
  7.  */
  8. import java.io.*;
  9. import java.util.Scanner;
  10. public class BinaryConverter
  11. {
  12.     public static void main(String [] args) {
  13.         Scanner getInput = new Scanner(System.in);
  14.        
  15.         System.out.println("Input an integer to be converted to binary:");
  16.        
  17.         int num = getInput.nextInt();
  18.        
  19.         conversionRecursion(num);
  20.        
  21.     }
  22.    
  23.    
  24.     public static void conversionRecursion(int num) {
  25.        
  26.         //So that nothing funky happens
  27.         if(num > 0) {
  28.            
  29.             //Recursive Code, continually getting 1s and 0s
  30.             conversionRecursion(num/2);
  31.            
  32.             //Now using Modulus we can get the remainder when divinding by 2, hence modulus 2.
  33.             //This sections only runs after the recursion has occured.
  34.             //Not println so that they're all on the same line
  35.             System.out.print(num%2);
  36.            
  37.             //The print statement is effectively the conversion to binary.
  38.         }
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement