Binary Calculator Assignment - java

For this lab, you will enter two numbers in base ten and translate
them to binary. You will then add the numbers in binary and print out
the result. All numbers entered will be between 0 and 255, inclusive,
and binary output is limited to 8 bits. This means that the sum of the
two added numbers will also be limited to 8 bits. If the sum of the
two numbers is more than 8 bits, please print the first 8 digits of
the sum and the message "Error: overflow". Your program should
represent binary numbers using integer arrays, with the ones digit
(2^0) stored at index 0, the twos digit (2^1) stored at index 1, all
the way up to the 2^7 digit stored at index 7. Your program should
include the following methods:
int[] convertToBinary(int b) Translates the parameter to a binary value and returns it stored as an array of ints.
void printBin(int b[]) Outputs the binary number stored in the array on one line. Please note, there should be exactly one space
between each output 0 or 1.
int[] addBin(int a[], int b[]) Adds the two binary numbers stored in the arrays, and returns the sum in a new array of ints.
When entering my code into CodeRunner (which tests the code and returns a grade back depending on the results of each test) I cannot seem to pass one of the tests. This is the message that I am getting:
*You had 43 out of 44 tests pass correctly. Your score is 97%.
The tests that failed were: Test: addBin() method Incorrect: Incorrect number returned*
Heres my code:
import java.util.Scanner;
class Main {
public static int[] convertToBinary(int a) {
int[] bin = {0, 0, 0, 0, 0, 0, 0, 0};
for (int i = bin.length - 1; i >= 0; i--) {
bin[i] = a % 2;
a = a / 2;
}
return bin;
}
public static void printBin(int[] b) {
int z;
for (z = 0; z < b.length; z++) {
System.out.print(b[z] + " ");
}
System.out.println();
}
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (added[0] + c[0] + d[0] == 1) {
added[0] = 1;
} else if ((added[0] + c[0] + d[0] == 2) || (added[0] + c[0] + d[0] == 3)) {
System.out.println("Error: overflow");
}
return added;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num1 = scan.nextInt();
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num2 = scan.nextInt();
int[] bin;
bin = convertToBinary(num1);
System.out.println("First binary number:");
printBin(bin);
int[] bin1 = bin;
bin = convertToBinary(num2);
System.out.println("Second binary number:");
printBin(bin);
int[] bin2 = bin;
System.out.println("Added:");
{
printBin(addBin(bin1, bin2));
}
}
}
If anyone could take a look at my code above and see if they could tell me what needs to be changed to fix the addbin() method so that it passes all of the tests, that'd be great! Any help is greatly appreciated even if you are not sure it would work! Thanks!

Hi first of all pardon my English but i guess your assignment accepts 1 and 255 too. So i added two of them and get 1 0 0 0 0 0 0 0 in your code. But i think it need to be 0 0 0 0 0 0 0 0 with an overflow error. So i changed your code a little bit.
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (remain!=0) {
System.out.println("Error: overflow");
}
return added;
}
It's my first answer on the site so i hope it works for your test

Related

How to can I sum some numbers in a random series?

I'm trying to make a program that generates random two-digit integers until I get a 10 or a 20. To then find the mount of numbers, the sum of the numbers less than 10, the sum of the numbers equal to 15, the sum of the numbers greater than 70. Can someone help me, please?
This is my code:
// Variables
int numRandom = 0, less10, equal15, more70;
// Process
txtS.setText("Random numbers: " + "\n");
for (int mountNum = 0; numRandom == 40 || numRandom == 20; mountNum++) {
numRandom = (int) (99 * Math.random());
txtS.append(numRandom + "\n");
}
You could just store the values directly and create variables for each case.
This is an example for you less than 10 case. (The 'if statement' would be contained inside your for loop).
int sumLessThanTen = 0;
int countLessThanTen = 0;
...
if(numRandom < 10){
sumLessThanTen += numRandom;
countLessThanTen++
}

How to reverse the order of an int without turning it into a string

I have been tasked with the assignment of creating a method that will take the 3 digit int input by the user and output its reverse (123 - 321). I am not allowed to convert the int to a string or I will lose points, I also am not allowed to print anywhere other than main.
public class Lab01
{
public int sumTheDigits(int num)
{
int sum = 0;
while(num > 0)
{
sum = sum + num % 10;
num = num/10;
}
return sum;
}
public int reverseTheOrder(int reverse)
{
return reverse;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Lab01 lab = new Lab01();
System.out.println("Enter a three digit number: ");
int theNum = input.nextInt();
int theSum = lab.sumTheDigits(theNum);
int theReverse = lab.reverseTheOrder(theSum);
System.out.println("The sum of the digits of " + theNum + " is " + theSum);
}
You need to use the following.
% the remainder operator
/ the division operator
* multiplication.
+ addition
Say you have a number 987
n = 987
r = n % 10 = 7 remainder when dividing by 10
n = n/10 = 98 integer division
Now repeat with n until n = 0, keeping track of r.
Once you understand this you can experiment (perhaps on paper first) to see how
to put them back in reverse order (using the last two operators). But remember that numbers ending in 0 like 980 will become 89 since leading 0's are dropped.
You can use below method to calculate reverse of a number.
public int reverseTheOrder(int reverse){
int result = 0;
while(reverse != 0){
int rem = reverse%10;
result = (result *10) + rem;
reverse /= 10;
}
return result;
}

Having trouble filling an array of binary numbers from an integer

This is the question we were assigned :
Nine coins are placed in a 3x3 matrix with some face up and some face down. You can represent the state of the coins using a 3x3 matrix with values 0 (heads) and 1 (tails). Here are some examples:
0 0 0 1 0 1 1 1 0
0 1 0 0 0 1 1 0 0
0 0 0 1 0 0 0 0 1
Each state can also be represented using a binary number. For example, the preceding matrices correspond to the numbers:
000010000 101001100 110100001
There are a total of 512 possibilities, so you can use decimal numbers 0, 1, 2, 3,...,511 to represent all the states of the matrix.
Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.
I want the method toBinary() to fill the array binaryNumbers. I realized that this does not fill in 0s to the left. I have to think that through but is that the only thing that is the problem?
//https://www.geeksforgeeks.org/java-program-for-decimal-to-binary-conversion/
import java.util.Scanner;
public class HeadsAndTails {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int[] binaryNumbers = toBinary(num);
for (int i = 0; i < 9; i++) {
printArr(binaryNumbers);
System.out.print(binaryNumbers[1]);
}
}
public static int[] toBinary(int inputtedNumber) {
int[] binaryNum = new int[9];
int i = 0;
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
inputtedNumber++;
} return binaryNum;
}
public static void printArr(int[] arr) {
for (int i = 0; i < 9; i++) {
if (arr[i] == 0) {
System.out.print("H ");
} else {
System.out.print("T ");
}
if (arr[i+1] % 3 == 0) {
System.out.println();
} System.out.print(arr[i]);
}
}
}
Looks like you are incrementing the wrong variable in your while loop:
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
i++; // NOT inputtedNumber
} return binaryNum;
Also note, a new int[9] is probably already initialized to 0, but if not, you could just loop 9 times, rather than until the inputtedNumber is 0:
for (int i = 0; i < 9; i++) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
}
return binaryNum;
Finally, I think your array might be backwards when you're done, so you may need to reverse it or output it in reverse order
I realize this is a homework assignment so you should stick with your current approach. However, sometimes it can be fun to see what can be achieved using the built in features of Java.
The Integer class has a method toBinaryString that's a good starting point:
int n = 23;
String s1 = Integer.toBinaryString(n);
System.out.println(s1);
Output: 10111
But as we can see, this omits leading 0s. We can get these back by making sure our number has a significant digit in the 10th place, using a little bit-twiddling:
String s2 = Integer.toBinaryString(1<<9 | n);
System.out.println(s2);
Output: 1000010111
But now we have a leading 1 that we don't want. We'll strip this off using String.substring, and while we're at it we'll use String.replace to replace 0 with H and 1 with T:
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
System.out.println(s3);
Output: HHHHTHTTT
Now we can print this string in matrix form, again using substring to extract each line and replaceAll to insert the desired spaces:
for(int i=0; i<9; i+=3)
System.out.println(s3.substring(i, i+3).replaceAll("", " ").trim());
Output:
H H H
H T H
T T T
If we're up for a bit of regex wizardry (found here and here) we can do even better:
for(String sl : s3.split("(?<=\\G.{3})"))
System.out.println(sl.replaceAll(".(?=.)", "$0 "));
Putting it all together we get:
int n = 23;
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
for(String s : s3.split("(?<=\\G.{3})"))
System.out.println(s.replaceAll(".(?=.)", "$0 "));

Adding numbers digits to number

For my program, I'd want to code an array 1-100. In that array, I want to store the number + their digits. For example, if the number is 6 the stored value would be 6 because of 6 + 6 = 12. If the number is 17 the stored value should be 25 because 17 + 1 + 7 = 25. I want to do it for every number. My code has a method and 2 for loops but currently outputs everything as 0; Here's my code.
public class GeneratedNums {
public static void main(String[] args) {
int [] numbers = new int [101];
for ( int x=0; x < 101; x++){
numbers[x] = sumDigits (x);
}
for ( int x=0; x < numbers.length; x++){
System.out.println(x + ": " + numbers[x]);
}
}
public static int sumDigits ( int num) {
int sum = num;
while ( num != 0){
num += num%10;
num /= 10;
}
return num;
}
}
You should be adding the result of modulo operation to sum. And you should return sum.
while ( num != 0){
sum += num % 10;
num /= 10;
}
return sum;
You don't need these many loops, you can improve it by caching the previous outputs and reusing it (Dynamic programming tabulation). Considering you don't have values greater than 100 following code can work for you
public static int sumDigits(int num) {
int[] cache = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 };
int sum = num + cache[num % 10] + cache[num / 10];
return sum;
}
basically, I've cached outputs for first 10 inputs.
FYI, you can make scale the program for larger inputs by storing the previous outputs in HashMap

Incorrect Output for Project Euler #2 - Java

The Word Problem I'm trying to solve:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I'm sure you've seen questions about this problem on Project Euler before, but I'm not sure why my solution doesn't work, so I'm hoping you can help!
public class Problem2Fibonacci {
public static void main(String[] args) {
/* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */
int sum = 0; // This is the running sum
int num1 = 1; // This is the first number to add
int num2 = 2; // This is the second number
int even1 = 0;
int even2 = 0;
int evensum = 0;
while (num2 <= 4000000){ // If i check num2 for the 4000000 cap, num will always be lower
sum = num1 + num2; // Add the first 2 numbers to get the 3rd
if(num2 % 2 == 0){ // if num2 is even
even1 = num2; // make even1 equal to num2
}
if(sum % 2 == 0){ // if sum is even
even2 = sum; // make even2 equal to sum
}
if (even1 != 0 && even2 != 0){ // If even1 and even2 both have values
evensum = even1 + even2; // add them together to make the current evensum
even2 = evensum;
}
num1 = num2;
num2 = sum;
System.out.println("The current sum is: " + sum);
System.out.println("The current Even sum is: " + evensum);
}
}
}
So my 2 questions are,
1. Why doesn't my plan to get sum of even numbers work correctly?
and
2. The last time my loop runs, it uses a num2 that is > 4000000. Why?
Thanks!
This should help you :
int first = 0;
int second = 1;
int nextInSeq =first+second;
int sum =0;
while(nextInSeq < 4000000) {
first = second;
second = nextInSeq;
nextInSeq = first + second;
if(nextInSeq % 2 ==0)
sum = sum + nextInSeq;
System.out.println("Current Sum = " + sum);
}
System.out.println("Sum = " + sum);
For your piece of code : even1 and even2 are not required and they are carrying value they hold from previous iterations as you continue.

Categories

Resources