|
|
2
|
+ The second method toBinary() converts a decimal number to binary. We create a boolean variable that stores whether the decimal number is positive or negative, then we use the absolute value of the decimal number. This allows us to convert the number as a positive number, then add a negative sign back in at the end of the method of necessary with a conditional statement and the stored boolean value. The actual number conversion takes place in a while loop that checks whether or not there is a remainder of 1 or 0 when you divide the decimal number by 2. The resulting digit is added to a string. The decimal number is then divided by 2 and contines to loop until the decimal number is equal to 1 or 0. We then run an assert statement to check that only 0s and 1s were concated to the string. We then add the final 1 or zero to the string that is stored in the base10Num variable. We then run the result (binary string) through a method from this class that double checks that the binary number only consists of 0s and 1s. Lastly we return to the boolean storing the positive or negative value, and add a "-" to the string is the number is suppose to be negative.
|