Frage

Please explain how this converts decimal to binary:

import java.util.*;

public class decimalToBinaryTest {
    public static void main(String[] args) {

        int number;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a positive interger");
        number = in.nextInt();

        if (number < 0) {
            System.out.println("Not a positive interger");
        }

        else {
            System.out.print("Convert to binary is: ");
            System.out.print(binaryform(number) + ".");
        }
    }

    private static Object binaryform(int number) {

        int remainder;

        if (number <= 1) {
            System.out.print(number);
            return null;
        }

        remainder = number % 2;
        binaryform(number >> 1);
        System.out.print(remainder);
        {
            return " ";
        }
    }
}

I mainly don't get the bit in private static object. Or the return " ". I really don't see how it does but it works. If you enter 10 it displays: Convert to binary is: 1010.

Do I need the >> 1 or can it be *0.5

War es hilfreich?

Lösung

There are two important moments in this code:

binaryform(number >> 1);

first: recursion. Call function from this function (foo() {foo();} second: bitwise. >>1 - shift number for 1 bit, it's the same to devide by 2.

every recursion iteration, code devide number by 2 and print reminder AFTER recursion function works (from last to first). It's like:

{
  {
    {
      {
      print inner (fourth iteration
      }
    print before inner (third iteration)
    }
  print before before inner (second iteration)
  }
print outer (first iteration)
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top