I am trying to convert a number in base 10 to a number in base 2, but I have a problem. When I run the code, I get the base 2 number in the wrong order. For example, I input 54 and get 110110 instead of 011011, the correct value.
import java.util.Scanner;
public class DecimalToBinary
{
public static void main(String arg[]){
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
quotient = quotient / 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
System.out.print (remainder);
} while (quotient != 0);
}
}
Java has a built-in method to do this:
Integer.toString(int i, int radix);
where
i is your base ten number, and
radix is the base you want it in, in your case, 2.
It will return a string in binary.
Another inbuilt java function for this is
Integer.toBinaryString(int num)
where num is the base 10 number you want to convert
Base 10 to Base 2 should Reverse output,I think you can use array,then reverse output array
public static void main(String arg[]){
int quotient;
int remainder;
List<Integer> arrayList=new ArrayList<Integer>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
quotient = quotient / 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
// System.out.print (remainder);
arrayList.add(remainder);
} while (quotient != 0);
ListIterator<Integer> li;
for (li = arrayList.listIterator(); li.hasNext();) {// 将游标定位到列表结尾
li.next();
}
for (; li.hasPrevious();) {// 逆序输出列表中的元素
System.out.print(li.previous() + " ");
}
}
try this solution, its simple:
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
Stack<Integer> s=new Stack<Integer>();
do {
remainder = quotient % 2;
quotient = quotient / 2;
s.add(remainder);
// String x = String.valueOf(remainder);
// System.out.print(x);
//System.out.print (remainder);
} while (quotient != 0);
while(!s.isEmpty()){
System.out.print(s.pop());
}
I was able to fix your code
public class CustomDecimalToBinary {
public static void Dec2Bin() {
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
System.out.print (remainder);
} while ((quotient /= 2) != 0);
}
}
Example output:
Please enter a decimal number:
54
011011
EDIT: It appears I solved the problem to get your desired output but your code produces the correct output...
Related
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;
}
Can not for the life of me figure out why my average is not displaying correctly I've looked at it for like 2 hours.
import java.util.Scanner;
public class midterm
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int examScore =0;
int averageExamScore = 0;
int numStudent=0;
int sum=0;
while(examScore >= 0)
{
System.out.println("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
numStudent++;
sum = sum + examScore;
}
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
}
else
{
System.out.println("No scores to average");
}
}
}
The issue here is integer division.
averageExamScore = sum/numStudent;
All three of these arguments are integers, which means:
If you cast a part of your quotient to double, you'd lose precision (and fail compilation)
Example:
averageExamScore = (double)sum/numStudent; // wouldn't compile
The floor of the quotient sum/numStudent is provided instead of the whole number (so for a number like 4.9 you'd get 4).
You can fix this in a few ways:
Declare averageExamScore to be a double. This is required.
Either cast sum or numStudent to a double, or change their type to double.
You have defined averageExamScore as an integer, so integer arithmetic will be applied.
e.g.
5 / 2 == 2
1 / 2 == 0
Make averageExamScore into a double, and also cast your other integers to doubles.
Edit
To print out
do
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
System.out.println ("average score is " + averageExamScore );
}
Go through the following code,
public class MidTerm {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int examScore = 0;
double averageExamScore = 0;
int numStudent = 0;
int sum = 0;
while (true) {
System.out.print("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
if (examScore >= 0) {
numStudent++;
sum += examScore;
} else break;
}
if (numStudent > 0) {
averageExamScore = sum / numStudent;
System.out.println("Avarage score is : " + averageExamScore);
} else System.out.println("No scores to average");
}
}
averageExamScore variable should be a double otherwise it can not stored floating point values
Good Luck !!!
When I run it I get this:
Enter 2 Integers, Do note that you will Get a Quotient and a Remainder.
Enter the First Number: 3
Now enter the Second Number: 9
Your Quotient is: 0
Your Remainder is: 3
It should be:
Enter 2 Integers, Do note that you will Get a Quotient and a Remainder.
Enter the First Number: 3
Now enter the Second Number: 9
Your Quotient is: 3
Your Remainder is: 0
Code:
import java.util.Scanner;
public class Remainder {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int a = 0, b = 0, quotient, remainder;
int smallerNumber = 0;
int biggerNumber = 0;
System.out.println("Enter 2 Integers, Do note that you will Get a Quotient and a Remainder.");
System.out.print("Enter the First Number: ");
a = reader.nextInt();
System.out.print("Now enter the Second Number: ");
b = reader.nextInt();
remainder = (a % b);
quotient = (a / b);
remainder = (a % b);
if(a > b){
biggerNumber = a;
a = b;
}else{
smallerNumber = a;
biggerNumber = b;
}
System.out.print("Your Quotient is: ");
System.out.println(quotient);
if (remainder > 0){
System.out.print("Your Remainder is: ");
System.out.println(remainder);
}
}
}
You are entering the numbers in the wrong order. You are doing a / b, and 3 / 9 in integer math is zero. Enter 9 first, and 3 second, and things will work.
Note also that you are looking for the bigger and smaller number after computing the remainder and quotient (and you compute the former twice). Swap the order of the code, and divide bigger/smaller for better results...
System.out.println("Enter 2 Integers, Do note that you will Get a Quotient and a Remainder.");
System.out.print("Enter the First Number: ");
a = reader.nextInt();
System.out.print("Now enter the Second Number: ");
b = reader.nextInt();
if(a > b){
biggerNumber = a;
smallerNumber = b;
}
else {
smallerNumber = a;
biggerNumber = b;
}
remainder = biggerNumber % smallerNumber;
quotient = biggerNumber / smallerNumber;
You have a and b backwards. Instead,
quotient = b / a;
remainder = b % a;
Also, a and b should probably be renamed to first and second...
There is something that I tried to fix over and over and I couldn't.
So the program asks a user for 3 numbers a then asks for the percentage they want to add then these numbers goes to a void method:
So its like this:
public static void main(String[] args) {
System.out.print("Number 1: ");
X1 = s.nextLong();
System.out.print("Number 2: ");
W1 = s.nextLong();
System.out.print("Number 3: ");
Z1 = s.nextLong();
System.out.print("Percentage 1: ");
int a = s.nextInt();
System.out.print("Percentage 2: ");
int b = s.nextInt();
System.out.print("Percentage 3: ");
int c = s.nextInt();
Number(a,b,c);
}
public static void Number(int a, int b, int c)
{
X1 = (long) (X1*(a/100 + 1));
W1 = (long) (W1*(b/100 + 1));
Z1 = (long) (Z1*(c/100 + 1));
}
But if I try to type the results the numbers don't change.
Note: X1,W1 and Z1 are all used as static long
And thanks in advance.
Unless a,b,c >= 100, the expression
a/100
will be 0. Hence
something * (a/100 +1)
is
something * 1
You are dividing the integer parameters by the integer 100 using--you guessed it--integer arithmetic which results in 0 for any value less than 100. Use 100.0 to force floating point precision.
X1 = (long) (X1*(a / 100.0 + 1.0));
...
Divide your number by 100.0 in the Number method.
i have written a program to find out the number of digit in a given number in java. Is it a good way to do it and what is the time complexity of the program:
import java.util.*;
public class Inst {
/**
* #param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
for(int n=0;n<200000;n++)
{
double b=Math.pow(10, n);
double d=a/b;
if(d>=0 & d<=9)
{
System.out.println("The number has "+(n+1)+" DIGITS");
break;
}
}
}
}
How about this?
double input = Input;
int length = (input + "").length();
import java.util.*;
public class JavaLength {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Double d = sc.nextDouble();
String dString = d.toString();
System.out.println(d);
if(dString.contains(".")){
System.out.println("Total Characters: " + (dString.length() -1 ));
}else{
System.out.println("Total Characters: " + (dString.length()));
} /*-1 for the '.' in between, if it exists!*/
}
FWIW, the most efficient way to test the number of (decimal) digits needed to represent an integer will be a tree of if / else tests. The complexity will be O(1), but the code will be UGLY (but portable); e.g.
int num = ...
if (num >= 0)
if (num < 1000000)
if (num < 10000)
if (num < 100)
if (num < 10)
return 1
else
return 2
else
...
else
...
else
...
else
...
Using pow / log is not generally a good solution, as there may be a number close to a power of ten that rounds to the next integer. In double precision one should be able to precisely store all 15 digit numbers for which log10 should be absolutely < 15. In reality log10(10^15 - 100) still rounds to 15.
One will be stuck with the same algorithms, that are internally used in decimal to string conversions:
trial division:
while (i > 0) { i=i/10; count++; }
trial multiplication:
j=10; while (i >= j) { j*=10; count++; }
trial division from msb to lsb converting to string;
j=10000000; while (i>0) {
while (i>=j) { digit++;i-=j;};
j/=10; *str++=digit+'0'; digit=0:
}
Binary to bcd conversion using double dabble algorithm where each digit is represented by reduced set of hexadecimal digits (omitting a-f).
This logic was originally written in c++, but i believe is the best way to find number of digits, store them in reverse order and find sum of digits.
int n;
int count=0, sum=0;
int j=0;
int ar[10]; //array to store digits
cin>> n; //input number
do{
if((n/10)==0){
count++;
ar[j]=n;
break;
}
else{
count++;
ar[j]= (n%10);
j++;
n=int(n/10);
}
}
`
while((n/10)!=0||(n%10)!=0);
cout<<"The number of digits is: "<<count<<"\n"<<"The reverse number is: ";
for(int u=0;u<count;u++){
cout<<ar[u];
sum+=ar[u];
}
cout<<"\n"<< "Sum of digits is: "<< sum;
}`