In: Computer Science
Background: Recall from the lecture notes that an integer x can
be represented as a vector [xw−1, xw−2, . . . , x0],
where w is the number of bits used to represent x. As a fun
exercise, let us consider a problem where we want to
partition x into two new numbers, labelled y and z. We can do this
by scanning through the bits of x from the least
significant bit (lsb) to the most significant bit (msb). We form
the new integers, y & z, according to the following
rule. Anytime a 1 is encountered during the scan through x we place
a 1 in either y or z in an alternating pattern.
Moreover, the bits are placed into the new integers at the same bit
position as found in the original integer x. Below
is an example.
Let x = (13)10 = (1101)2. Then, scanning from lsb to msb gives the
following result.
• Position 0: x0 = 1. Thus, y0 = 1, giving y = (0001)2.
• Position 1: x1 = 0. Thus, nothing happens.
• Position 2: x2 = 1. Thus, z2 = 1, giving z = (0100)2.
• Position 3: x3 = 1. Thus, y3 = 1, giving y = (1001)2.
The final result is that y = (1001)2 = (9)10 and z = (0100)2 =
(4)10.
Problem: Write a Java program that takes an integer x as an input
and produces y and z as an output.
Sample Execution:
Enter an integer x
13
y z
9 4
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== import java.util.Scanner; public class Converter { public static int toDec(String binary) { int dec = 0; int power = 1; for (int i = binary.length() - 1; i >= 0; i--) { if (binary.charAt(i) == '1') dec += power; power *= 2; } return dec; } public static String toBin(int decimal) { String bin = ""; while (decimal > 0) { bin = String.valueOf(decimal % 2) + bin; decimal /= 2; } return bin; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int x = scanner.nextInt(); String binX = toBin(x); String y = "", z = ""; boolean alternating = true; for (int i = binX.length() - 1; i >= 0; i--) { if (binX.charAt(i) == '0') { y = "0" + y; z = "0" + z; } else { if(alternating){ y = "1"+y; z = "0" + z; alternating = !alternating; }else{ y = "0"+y; z = "1" + z; alternating = !alternating; } } } System.out.println("y = "+ toDec(y)); System.out.println("z = "+ toDec(z)); } }
=================================================================