Count number of zeros after decimal point in Java - java

How can I count the 0s after a decimal point? For example, 0.0003 has 3 zeros, 0.03 has 1 zero and 0.00000045 has 6 zeros.

One approach is to keep multiplying by 10 until your number is greater than one; then count how many times you had to multiply by 10 and subtract 1.
double num = 0.00000045;
int zeros = 0;
while (num < 1) {
num *= 10;
zeros++;
}
zeros -= 1;
System.out.println(zeros);
6
If you have other non-zero digits before the decimal point, you can trim those off with something like num = num % 1. If your number is negative, then just take its absolute value.

(int)Math.log10(1/(x%1))
I think this short formula should work correct [for positive x - if it can be negative, we add taking of absolute value] - or there are some cases when it doesn't?

You could do this using Strings. First get a substring of digits after decimal point. Then convert that into a char array. Then loop through it and count the number of zeroes.

Related

Binary Converter Java

I am trying to make a converter that converts decimal into binary, there is a catch tho, I can't use any other loops or statements except
while (){}
And I can't figure out how to start subtracting the number that fits into the decimal when it can and not using any if statements. Does anyone have any suggestions?
import java.util.Scanner;
public class Converter{
static Scanner input = new Scanner (System.in);
public static void main (String[] args){
System.out.println ("What is the number in the decimal system that you want to convert to binary?");
int dec = input.nextInt();
int sqr = 1024;
int rem;
while (dec != 0){
rem = dec / sqr;
sqr = sqr / 2;
System.out.print(rem);
}
}
}
Try this:
import java.util.Scanner;
public class Converter {
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
System.out.println("What is the number in the decimal system that you want to convert to binary?");
int dec = input.nextInt();
int div = 128;
while (div > 0) {
System.out.print(dec / div);
dec = dec % div;
div >>= 1; // equivalent to div /= 2
}
System.out.println();
}
}
Now, let's go through the code and try to understand what's going on. I'm assuming that the maximum size is 8 bits, so the variable div is set to 2n-1 where n = 1. If you need 16 bits, div would be 32768.
The programme starts from that value and attempts to do an integer division of the given number by the divider. And the nice thing about it is that it will yield 1 if the number is greater than or equal to the divider, and 0 otherwise.
So, if the number we're trying to convert is 42, then dividing it by 128 yields 0, so we know that the first digit of our binary number is 0.
After that, we set the number to be the remainder of the integer division, and we divide the divider by two. I'm doing this with a bit shift right (div >>= 1), but you could also use a divider-assignment (div /= 2).
By now, the divider is 64, and the number is still 42. If we do the operation again, we again get 0.
At the third iteration, we divide 42 by 32, and this yields 1. So our binary digits so far are 001. We set the number to be the remainder of the division, which is 10.
Continuing this, we end up with the binary number 00101010. The loop ends when the divider div is zero and there's nothing left to divide.
Try to understand, step by step, how the programme works. It's simple, but it can be very difficult to come up with a simple solution. In this case, it's applied mathematics, and knowing how integer maths work in Java. That comes with experience, which you'll get in due time.
Your code has some Problem. It is more easier to convert a decimal to binary. fro example:
int num = 5;
StringBuilder bin = new StringBuilder();
while (num > 0) {
bin.append(num % 2);
num /= 2;
}
System.out.println(bin.reverse());
I use StringBuilder to reverse my String and I prefer String because length of binary can be anything. if you use int or long, maybe overflow happen.
Update
if you you want to use primitive types only, you can do something like this but overflow may happen:
long reversedBin = 0, Bin = 0;
while (n > 0) {
reversedBin = reversedBin * 10 + (n % 2);
n /= 2;
}
while (reversedBin > 0) {
Bin = Bin * 10 + (reversedBin % 10);
reversedBin /= 10;
}
System.out.println(Bin);
Remember the algorithm to convert from decimal to binary.
Let n be a number in decimal representation:
digit_list = new empty stack
while n>0 do
digit = n%2
push digit in stack
n = n/2
end while
binary = new empty string
while digit_list is not empty do
character = pop from stack
append character to binary
end while
Java provides a generic class Stack that you can use as a data structure. You could also use lists, but remember to take the digits in the inverse order you have calculated them.
find the base 2 log of the number and floor it to find the number of bits needed. then integer divide by that bits place in 2's power and subtract that from the original number repeat until 0. doesn't work for negative. there are better solutions but this one is mine
int bits = (int) Math.floor(Math.log((double) dec) / Math.log((double) 2));
System.out.println("BITS:" + bits);
while (dec > 0) {
int twoPow = (int) Math.pow((double) 2, (double) bits);
rem = dec / twoPow;
dec = dec - rem * twoPow;
bits--;
System.out.print(rem);
}

find Factorial of no. It is working fine but i am not able to understand why its giving me factorial 0 for no 56,89,77 and other some numbers

This is my code for factorial program. it is working fine but i am not able to understand why its giving me factorial 0 for no 56,89,77 and other some numbers.
private static void factorial() {
int resultant = 1, i;
System.out.println("Please Enter any number to find factorial : ");
Scanner scan = new Scanner(System.in);
int fact = scan.nextInt();
for (i = 1; i <= fact; i++) {
resultant = resultant * i;
}
System.out.println("Factorial of number : " + resultant);
}
You should know the size of int is fixed to 32 bits. When ever your computation results in producing a large number that cannot fit into those 32 bits, some bits will get overflowed producing a wrong result. You can try with this code.
private static void factorial() {
int resultant = 1, i;
System.out.println("Please Enter any number to find factorial : ");
Scanner scan = new Scanner(System.in);
int fact = scan.nextInt();
for (i = 1; i <= fact; i++) {
int test=resultant;
resultant = resultant * i;
if(resultant<test){
system.out.println("Looks like overflow occured");
}
}
System.out.println("Factorial of number : " + resultant);
}
Better way will be to use BigInteger instead of int.
Every even number that is part of the product contributes a trailing zero to the factorial. Actually to be more precise, the trailing zero count of a (unlimited precision) product is the sum of the trailing zero counts of the inputs. In finite precision the number of trailing zeroes is obviously limited by the size of the number.
So eventually, and this happens pretty quickly, the number of trailing zeroes becomes greater than or equal to 32, in which case all bits of an int would be zero. The same thing of course happens with long, a little later, at 64 trailing zeroes. And some time before that, even though the result is not totally zero yet, it would already have stopped matching what the result would have been in unlimited precision.
For example 34! in hexadecimal is
de1bc4d19efcac82445da75b00000000
The 8 least significant digits would be what you would get if you computed it with 32 bit integers, and all those digits are zero.
Factorial of such large numbers will be very large. You have to use a data type that can store very large numbers (we are talking about billions and trillions). BigInteger data type may work. Give it a try.

Performing way to limit double accuracy

I want manage numbers on a range from:
from 0,001 to 999,999
For representation reasons, I want to drop some of the accuracy keeping only the 3 most important digits of the number.
For the number 123,12 I expect the result 123.
For the number 12,123 I expect the result 12,1.
For the number 0,001 I expect the result 0,001.
The best solution I thought of is transforming the number into a String, and back again to double, this way:
number = number*1000;
String s = new String(number);
s = s.substr(0, 3) + "000";
number = Double.parseDouble(s);
number = number/1000;
This does the job but it looks both poorly performing and not elegant.
Any more clever alternative?
Thank you!
Here's a somewhat-convoluted answer that doesn't require the use of any conversion to String:
final int numDigits = 3;
double d = 12.123;
int counter;
for (counter = 0; counter < numDigits && d < Math.pow(10, numDigits - 1); counter++) {
d *= 10;
}
d = Math.floor(d);
d /= Math.pow(10, counter);
System.out.println(d);
Output: 12.1
Essentially it multiplies the double by 10 until it reaches the largest value under 1000 (your maximum value is 999.999), keeping track of how many times it has been multiplied. It then performs the floor function to get rid of any precision to the right of the decimal point. Finally, we divide the number by 10, counter times, which provides us with the first 3 significant figures.
Perhaps use this RegEx to make the code more concise?
^[,0]{0,6}(\d{3}|\d{2},\d|\d,\d{2})

Reverse an existing number

Could you explain me how this code works? I have tried it with any input and it always gives right result. I think that they key its the line reversenum = reversenum * 10;but i need some explanation on it.
public static void main(String args[]) {
int num=123456789;
int reversenum =0;
while( num != 0 ){
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
System.out.println("Reverse of specified number is: "+reversenum);
}
You start with 123456789 (num) and 0 (reversenum). Then, you multiply reversenum by 10: it remains 0. num % 10 is the remainder when num is divided by 10: this is 9, which becomes reversenum. num is then divided by 10, but integer division gets the floor of fractional results, so you will get 12345678 as num (NOT 12345678.9). In the second pass, 9 (reversenum) is multiplied by 10 to get 90, and the last digit of num is added: 8. reversenum becomes 98 and num becomes 1234567. This keeps going until num is 0 and reversenum is 987654321; the while loop's condition will then be satisfied.
Essentially, what the code does is:
Take off the units digit from the original number.
Add that digit to the rightmost position of the reverse.
Multiply the reverse by 10, so the digit shifts up one.
Divide the original by 10, to move on to the next digit.
This happens until there are no more digits left.
At the end of each pass through the while loop, the current last digit of num is removed and it becomes the last digit of reversenum. So the last digit of num is removed and it becomes the first digit added to reversenum (and thus the first digit of reversenum). Then it takes what was originally the next to last digit of num and it becomes the second digit added to reversenum (and thus the second digit of reversenum). This continues until no digits are left to move.
Let's look at the first pass:
reversenum becomes 0*10, which is 0. Then you add num%10, which is 9. So reversenum becomes 9.
Meanwhile the integer division makes num become 12345678
Looking at the next pass:
reversnum becomes 9*10 which is 90, then add num%10 which is 8, so reversenum becomes 98.
Meanwhile integer division makes num become 1234567.
small warning
What would you think the reverse of 90 is? You should be aware of this case.
Let your number be 12345. We extract the digits from the end. First we find the remainder when 12345 divided by 10. The remainder comes to be 5.Now we add this to our reversenum which is supposed to store the reverse number. Then we divide 12345 by 10 . As a integer divided by a integer gives a integer value . Therefore
num = 12345/10 = 1234
We multiply
reversenum by 10 so that reversenum becomes 50 and again add the remainder to reversenum So 2nd time reversenum becomes 54.Then we extract the last digit of 1234 (num variable). As you can see this continues till the total number is reversed i.e, num=0 (there are no more digits to be extracted).
Inside the while statement it is multiplying the reversenum variable by ten, then adding the remainder of the num/10 to reversenum, and then finally it divides the num by ten. It is possible for this while statement to end because since each variable is an int, dividing num by ten will always produce the rounded up version of num/10 if num is not evenly divisible by 10.

Smallest n bit Binary Number Creation in Java

How can we create a smallest binary number whose length is given.
For example,
the smallest binary number of length 4 is 1000
the smallest binary number of length 3 is 100.
I am not able to come up with any algorithm since length is only given.
This process of creating the number is to be done
numerous time with varying length.
What can be the code for that?
That is easy: 0, 00, 000, 0000, 00000, ....
On the serious note, binary is just another notation. What you have is a simple computation like this
binary 1 = decimal 1
binary 10 = decimal 2
binary 100 = decimal 4
binary 1000 = decimal 8
So you can do
int myNumber = 1;
for (int i = 1; i < LENGTH; i++)
myNumber = myNumber * 2;
Or use
myNumber = Math.pow(2, LENGTH - 1);

Categories