SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:3 | ISBN:9780136091813 | Edition: 2

Question

Write a method called toBinary that accepts an integer as a parameter and returns a String containing that integer’s binary representation. For example, the call of printBinary(44) should return "101100".

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

public class DecimalToBinary {

	public static void toBinary(int value) {

		// take an array to store the binary value
		int[] binaryArray = new int[65];
		
		// j to represent index value
		int j = 0;
		
		while (value > 0) {
			binaryArray[j++] = value % 2;
			value = value / 2;
			
		}
		
		// array was stored in reverse order
		// use forloop to print it right order

		for (int i = j - 1; i >= 0; i--) {
			System.out.print(binaryArray[i]);
		}
		System.out.println();
	}

	public static void main(String[] args) {
		DecimalToBinary.toBinary(6654654);
		DecimalToBinary.toBinary(32);
		DecimalToBinary.toBinary(66);
		DecimalToBinary.toBinary(2);

	}

}
Output:

11001011000101010111110
100000
1000010
10

 

0 0

Discussions

Post the discussion to improve the above solution.