There are many ways to convert a rational number into a decimal with a recurring part (in other words, 10/3=3.(3)
, where (3)
indicates that it repeats forever). But these only work if the numerator and denominator are integers. What can we do if the numerator or denominator is a double? For example, how can we find that
1/0.3 = 3.(3)
UPDATE: This works but only for int numbers.
http://www.programcreek.com/2014/03/leetcode-fraction-to-recurring-decimal-java/
Let split the problem in two pieces:
1/0.3
to N/M
formN/M
to a.b(c)
formLets convert 0.3
to M/N
form (which give us 3/10
).
String input = "123.456";
String[] parts = input.split("\\.");
String whole = parts[0];
String fraction = parts[1];
int wholeInt = Integer.parseInt(whole);
int fractionInt = Integer.parseInt(fraction);
int multiplier = pow10(fraction.length());
int n = wholeInt * multiplier + fractionInt;
int m = multiplier;
System.out.println(n + "/" + m);
I used function pow10
which simply returns 10 power input.
Now we need divide 1
by 10/3
it is easy N1/M1
divided by N2/M2
it is simply (N1*M2)/(N2*M1)
.
We get our result in form N/M
now (we also need to normalize it by dividing both part by GCD(N, M
)
Now we ready to solve main problem.
First of all get whole part
int whole = n/m;
then find fraction and repeating part
int current = n%m;
StringBuilder sb = new StringBuilder();
List<Integer> controlSet = new ArrayList<>();
while((!controlSet.contains(current))){
int currentDigit = current *10 / m;
sb.append(currentDigit);
controlSet.add(current);
current = current *10 - m * currentDigit;
}
String fraction = sb.toString().substring(0, controlSet.indexOf(current));
String repeat = sb.toString().substring(controlSet.indexOf(current));
Here we just divide in loop getting result number by number.
Main trick then number starts to repeat when we meet current
that we already use.
Now you need to take all parts together. Implement GCD
(lots of implementation over internet).