简体   繁体   中英

Converting Decimal value to Binary in Java

Here is my problem. In the following code, I have a void type method, but inside this method, I can still find a return .

Also, in the recursion call, I can find this >> operator.

So there are my questions :

  • Why using a return in a void function ?
  • Whats number >> 1 does it mean ?
import java.util.Scanner;
class Code {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your Decimal value here : ");
        int num = sc.nextInt();
        printBinaryform(num);
        System.out.println();
    }
    private static void printBinaryform(int number) {
        int remainder;
        if (number <= 1) {
            System.out.print(number);
            return; // KICK OUT OF THE RECURSION
        }
        remainder = number % 2;
        printBinaryform(number >> 1);
        System.out.print(remainder);
    }
}

In your code, the return; is used to leave the function. In an String function, we would have had the return keyword, follow by a String value, but in a void function return is just follow by nothing.

The >> operator is called a right shift. It is used for the bit shift. But this question already have an answer here :

What does “>>” mean in java

12 is 1100 in binary. A right shift (>> is the bitwise right shift operator) by one bit produces

1100 -> 0110

which comes out to be 6.

Thus we have that,

6 - 1 = 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM