why does the c value gets repeated in the given code? - java

1.This is my code to convert binary to decimal but its not working.The c value gets repeated for some reasons.
/**
* Created by Ranjan Yadav on 11.10.2016.
*/
public class BinaryToDecimal {
public static void main(String[] args) {
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
int binary = read.nextInt();
int total = 0;
int n = 1;
int c = 0;
int number = 0;
while (binary != 0) {
c = binary % ((int) Math.pow(10, n));
binary = binary / 10;
number = c * (int)(Math.pow(2, (n - 1)));
total += number;
++n;
}
System.out.printf("The decimal of the binary is %d", total);
}
}

You were increasing n by 1 and dividing binary by 10 raised to n at same time. Due to this, you were not able to fetch the unit's digit of binary number after 1st iteration. To solve this issue, you need to get binary modulo 10 (not 10 raised to n) in each iteration and also keep the statement of binary divided by 10.
I have simplified and also made some small changes to your code to increase readability. Here is the corrected main method :
public static void main (String[] args){
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
int binary = read.nextInt();
int total = 0;
int n = 0;
int c = 0;
int number = 0;
while (binary != 0) {
c = binary % 10;
binary = binary / 10;
number = c * (int)(Math.pow(2, n));
total += number;
++n;
}
System.out.println("The decimal of the binary is " + total);
}
The code is working and producing desired results. Let me know in case you have any further doubts.

You can just parse the integer with the parseInt method:
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = read.nextLine();
int decimal = Integer.parseInt(binary, 2); // 2 here means the string "binary" is in binary
If you're not allowed to use that, try this algorithm:
Create a variable total and make it 0.
Loop through the binary string with a for loop like this: for (int i = 0 ; i < binaryString.length() ; i++)
In each iteration, if the character is 1, add Math.pow(2, binaryString.length() - 1 - i). Otherwise do nothing.

Related

The sum of certain digits from an input number

I've been trying to sum a certain digit from a number, for example
Number: 5
Input: 54365
Output: The sum of 5's is 10
Second example:
Number: 5
Input: 5437555
Output: The sum of 5's is 20
I've managed to separate the digits yet I couldn't find the condition to sum
a certain number (for instance number 5 like the examples).
I'd appreciate to hear your idea of doing it
public static void main(String[] args) {
int sum = 0;
int number = MyConsole.readInt("Enter a number:");
while (number > 0) {
if (number % 10 == 8) {
sum += 8;
} else {
number /= 10;
}
}
System.out.println("The sum of 8's is:" + sum);
}
My way of separating the numbers.
Also i have a small program to get input instead of using scanner since we still haven't went through it in class.
Your requirement seems reasonably clear to me.
Given a number
final int number = 5;
And a starting number
final int input = 54365;
The easiest way is to convert that number to a String
final int inputStr = String.valueOf(input);
Then, you can filter each char for it, and sum them
final int sum =
inputStr.chars() // Get a Stream of ints, which represent the characters
.map(Character::getNumericValue) // Convert a char to its numeric representation
.filter(i -> i == number) // Filter for the designated number
.sum(); // Sum all the filtered integers
Output: 10
Using the same approach, but with an old-style for loop
final int input = 54365;
final int inputStr = String.valueOf(input);
final int number = 5;
int sum = 0;
for (final char c : inputStr.toCharArray()) {
final int n = Character.getNumericValue(c);
if (n == number) {
sum += number;
}
}
Your solution can work
int number = 5;
int input = 543655;
int sum = 0;
while (input > 0) {
if (input % 10 == number) {
sum += number;
}
input /= 10;
}

(Java)Why does my decimal to binary conversion method only work some of the time when counting consecutive integers in a character array?

I'm a novice Java coder working on a problem dealing with counting consecutive integers in the binary forms of numbers.
The numbers are read from the input, and converted to binary using the method called conversion. The binary form is then sent to a character array where the for loop checks for consecutive characters(specifically the number 1) and prints the maximum count as the final answer.
I've managed to get the code to a state where I feel it should be working, but I've only had success with about half of the test cases. The larger number conversions like 262,141 tend to produce incorrect answers. Can anyone tell me where I've gone wrong?
I have a suspicion that it's something to do with the character array, but after several hours of research I haven't been able to find a solution to my particular problem.
import java.io.*;
import java.util.*;
public class Solution {
public static int conversion(int decimal){//this will take the decimal from the input and convert it to binary
int result = 0;//the result from each step of the conversion
int base = 1;//used to multiply the remainder by 1, 10, 100 etc
while(decimal > 0){
int remainder = decimal % 2;//takes the remainder of the iteration
decimal = decimal / 2;//halves the decimal number
result = result + (remainder * base);//pseudo concatenation of the binary
base = base * 10;//increases the base multiplier to continue filling out the binary leftward
}
return result;//returns result after loop has finished
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();//scan the input to obtain the decimal number
int binaryForm = conversion(n);//convert the decimal to binary and assign to binaryForm variable
String stringForm = Integer.toString(binaryForm);//convert binaryForm to a String
int counter = 1;
int max = 1;
char testArray[] = stringForm.toCharArray();//send stringForm to fill out testArray
for(int i = 0; i < testArray.length - 1; i++){//loops through testArray to test stringForm values
if(testArray[i] == testArray[i + 1] && testArray[i] == '1'){//if consecutive values equal char 1, increase counter
counter += 1;
if(counter > max){
max = counter;//if counter is higher than current maxCounter, increase maxCounter
}
}
else {//if consecutive values do not equal 1, reset counter
counter = 1;
}
}
System.out.print(max);//print the maximum consecutive values for the decimal input when converted to binary
}
}
You are trying to create a binary representation of a decimal number using an integer. This will work for smaller numbers but it doesn't take long for you to reach an overflow. You should use a string representation of the binary number like so
String numBin = "";
while(num > 0)
{
numBin = num % 2 + numBin;
num = num / 2;
}
System.out.println("Binary Representation: " + numBin);
Then take that string and loop through it calculating the consecutive counts of 1's
int consecutiveCount = 0;
for(int i = 0; i < numBin.length() - 1; i++)
{
if(numBin.charAt(i) == '1' && numBin.charAt(i + 1) == '1')
{
consecutiveCount++;
}
}
System.out.println("Consecutive Count: " + consecutiveCount);
Output
Number: 261141
Binary Representation: 111111110000010101
Consecutive Count: 7
Number: 3
Binary Representation: 11
Consecutive Count: 1
Number: 18
Binary Representation: 10010
Consecutive Count: 0
Number: 1111111
Binary Representation: 100001111010001000111
Consecutive Count: 5

Java - beginner code, adding fractions

I have a school project due next week and I'm trying to crack the way to solve this question.
The problem was to develop a program that adds the fractions the user inputs until he types -1.
the input will always be in pair and positive numbers.
Must only use: int, for,while, if, scanner (so no break or arrays)
Preferably with the use of GCD since it's required to println the
reduced sum of fractions
So my questions are this:
can I use a while loop until user types -1 using the scanner?
Is it alright to use the 'while' to let a user type 'infinite' (I am aware that there is no such this in java) number of number until termination?
in the code of the previous question I wrote the common factor for
the equation, how do I write a common factor for an unknown number of
variables
Edit:
here is my code, the problem is, it only runs for 4*n numbers, I need it to be able to run for 2*n numbers: ( like 2/4 or 2/4+1/3+1/2)
Scanner myScanner=new Scanner(System.in);
int a;
int b;
int c;
int d;
int m = a*d + b*c;
int n = b*d;
int r = m%n;
while((a = myScanner.nextInt()) != -1)
{
b = myScanner.nextInt();
c = myScanner.nextInt();
d = myScanner.nextInt();
while (r != 0) {
m=n;
n=r;
r = m%n;
}
m = (a*d + b*c)/n;
n = (b*d)/n;
System.out.println(m);
System.out.println(n);
}
}
A.
It is possible to keep reading input from a scanner until a defined message (in this case pairs of numbers until -1 is entered)
Scanner scanner = new Scanner(System.in);
int num1;
int num2;
while((num1 = scanner.nextInt()) != -1)
{
num2 = scanner.nextInt();
//do stuff with num1 and num2
}
B.
The whole point of A. is to allow variable amounts of input from the user, so unless you have a reason for a hard limit, it should in theory take infinite input
C.
Instead of trying to compute the common factor before you have any numbers, it's easier to compute the common factor as you get the numbers
int newNumerator = numerator1 * denominator2 + numerator2 * denominator1;
int newDenominator = denominator1 * denominator2;
Keeping track of the current numerator and denominator, updating as you get more pairs
This can then have A. be applied to it for infinite input
Scanner scanner = new Scanner(System.in);
int numerator = 0;
int denominator = 0;
int tempNumer = 0;
int tempDenom = 0;
if((numerator = scanner.nextInt()) != -1)
{
denominator = scanner.nextInt();
while((tempNumer = scanner.nextInt()) != -1)
{
tempDenom = scanner.nextInt();
numerator = numerator * tempDenom + tempNumer * denominator;
denominator = denominator * tempDenom;
}
}

Reversing an integer in Java using a for loop

This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}

Binary to Decimal Conversion Java Code Bug

So I'm doing a project where I have to do conversions from binary numbers to decimals etc.
This is my code so far and there is a bug. In a binary number such as 1101 the decimal number that is suppose to come out is 13 but the number that comes out of the code is 11. This bug happens to all binary numbers that starts with a bunch of 1's and like a single 0.
import java.util.*; // imports everything in java.util
public class newCalculator{
* Conversion asks the user for a binary number. It converts the input to a decimal number
* using arrays and then displays the answer to the screen.
*/
public static void main (String[]args){ // creates the main method
binaryToDecimal(); //calls the user defined method binaryToDecimal
}
public static void binaryToDecimal() {
Scanner scan = new Scanner(System.in); // Creates a new Scanner
System.out.println("Input a Binary Number"); // Asks the user to input their number
String binary = scan.next(); // Creates a new String that stores the value of the input
char[] charArray = binary.toCharArray(); //Create a new Array and implements in the input
double answer = 0; // Creates a new double called answer setting it to zero
for (double index = 0; index < charArray.length; index++){//For loop
if (charArray[(int)index] == '1') {//If statement that allows the binary input to work
answer = answer + Math.pow(2.0, index);//Sets the answer with the math class power of 2
}
}
System.out.println(answer);//Prints out the final conversion result
/* Test Cases Expected Result Output
* 101 5 5
* 11 3 3
* 1 1 1
* 1101 13 11<--
* 111 7 7
* 1000001 65 65
* 1111 15 15
* 1001 9 9
* 11101 29 23<--
* 10101 21 21
*
*/
}
}
Your expected results are being calculated as if the binary string is read from right to left; however, your code is reading the binary string from left to right.
Change this:
for (double index = 0; index < charArray.length; index++){
To this:
for (double index = charArray.length - 1; index >= 0; index--) {
You should also change to using an integer as your index, like this:
for (int index = charArray.length - 1; index >= 0; index--) {
You are going through your bits in the wrong order. Your first index refers to the most significant bit, not the least significant bit.
Your call to Math.pow should be
answer = answer + Math.pow(2.0, (charArray.length - index - 1));
And as Tom Leese has already pointed out, please use an integer for your looping index.
Symmetry is the answer. If you look into all your tests inputs they all are symmetrical except 1101
Your algorithm is correct with the exception that instead of index in Math.pow you need to use Math.pow(2.0, charArray.length - i - 1), below is the correct implementation(really only small incremental change)
import java.util.Scanner;
public class NewCalc {
public static void main(String[] args) {
binaryToDecimal();
}
public static void binaryToDecimal() {
Scanner scan = new Scanner(System.in);
System.out.println("Input a Binary Number");
String binary = scan.next();
char[] charArray = binary.toCharArray();
double answer = 0;
for (int i = 0; i < charArray.length; i++) {
answer = charArray[i] == '1'
? answer + Math.pow(2.0, charArray.length - i - 1)
: answer;
}
System.out.println(answer);
}
}
package pdaproject;
import java.util.Scanner;
public class NewCalc {
public static void main(String[] args) {
binaryToDecimal();
}
// convert to decimal (base 10)
public static void binaryToDecimal() {
Scanner scan = new Scanner(System.in);
System.out.println("Input a Binary Number");
String binary = scan.next();
int answer = 0;
// process left to right
for (int i = 0; i < binary.length(); i++) {
answer = 2 * answer + (binary.charAt(i) == '1' ? 1 : 0);
}
System.out.println(answer);
}
}
public class BinaryToDecimal {
static int testcase1=1001;
public static void main(String[] args) {
BinaryToDecimal test = new BinaryToDecimal();
int result = test.convertBinaryToDecimal(testcase1);
System.out.println(result);
}
//write your code here
public int convertBinaryToDecimal(int binary)
{
int deci = 0;
int p=1;
int rem = 0;
while(binary>0)
{
rem = binary%10;
deci = deci+(rem*p);
p = p*2;
binary = binary/10;
}
return deci;
}
}

Categories