Problem:
To convert a number from decimal to binary, you simply divide by two until a quotient of zero is reached, then use the successive remainders in reverse order as the binary representation. Use a stack to store the remainder of the division and finally print the binary representation. The first line of input n is the number test cases. Each test case begins with an integer t representing the number of integers in the list, then t integers follow.
Output:
3
5
7
10
101
111
1010
5
7
10
101
111
1010
Solution:
import java.util.Scanner;
import java.util.Stack;
public class ProblemD {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
Scanner scan = new Scanner(System.in);
int numberOfExpressions = scan.nextInt();
int[] num = new int[numberOfExpressions];
for (int i = 0;i<numberOfExpressions;i++)
{
num[i] = scan.nextInt();
}
for (int i = 0;i<numberOfExpressions;i++)
{
if (num[i] == 0) {
System.out.println("0000");
} else if (num[i] == 1) {
System.out.println("0001");
} else {
while (num[i] != 0) {
int a = num[i] / 2;
int b = num[i] % 2;
stack.push(b);
num[i] = a;
}
}
while (!stack.empty()) {
System.out.print(stack.pop());
}
System.out.println(" ");
}
}
}
No comments :
Post a Comment