ZZULIOJ-1112: binary conversion (function topic) (Java)

Subject description:

Enter a decimal integer n, outputs the corresponding binary integer. Commonly used methods to convert "In addition modulo 2, in reverse order." A decimal number by 2 to obtain the remainder and quotient, the quotient obtained by dividing by 2, and so on, up until the quotient equals 0, to take down the remainder of the divided binary number that is asked for. For example, the calculation process 52 in terms of binary number as shown below:

52 divided by 2 a remainder obtained were 0,0,1,0,1,1, in reverse order, to obtain the corresponding 52 binary number 110100.

Thought a recursive calculation process described above is such that: the output of n / 2 corresponding to the binary number, then enter the 2%. Implementation of a recursive function as follows:

void convert(int n)

{

   if(n > 0)

   {

      It calls itself, the output of n / 2 corresponding to the binary number;

       Output n% 2;

    }

}

Try it!

 Input:

Enter a positive integer n. 

Output: 

The number n corresponding to the binary output. 

Sample input: 

52 

Sample output: 

110100 

code: 

import java.util.*;
public class Main
{
	public static void convert(int n)
	{
		if(n>0)
		{
			Main.convert(n/2);//n依次除以2
			System.out.print(n%2);//输出每次除以2之后的余数
		}
	}
	public static void main(String[] args)
	{
		Scanner input=new Scanner(System.in);
		int n=input.nextInt();
		Main.convert(n);
		input.close();
	}
}

 

Published 260 original articles · won praise 267 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43823808/article/details/103787619