Created
June 2, 2019 10:45
-
-
Save maheshj01/257539cf4ae343983cdf3e555779c5f7 to your computer and use it in GitHub Desktop.
Double to Mixed Fractions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
import java.text.*; | |
import java.math.*; | |
import java.util.regex.*; | |
public class Solution { | |
public static void main(String[] args) { | |
Scanner input = new Scanner(System.in); | |
int n = input.nextInt(); | |
for(int i = 0 ; i < n ; i++){ | |
double number = input.nextDouble(); | |
String s = Double.toString(number); | |
s = "0" + s.substring(s.indexOf(".")); | |
double decimal = Double.parseDouble(s); | |
int num = (int)number; | |
if(number-num==0){ | |
System.out.println(-1); | |
}else{ | |
int digits = s.substring(s.indexOf(".")).length()-1; | |
int denominator = (int)Math.pow(10,digits);//10000 | |
int numerator= (int)(denominator * decimal);//3242 | |
for(int divisor = 2 ;divisor <= numerator;divisor++){ | |
if(numerator % divisor==0 && denominator % divisor==0){ // if coommon divisor | |
numerator = numerator/divisor; | |
denominator = denominator/divisor; | |
divisor=2; | |
} | |
} | |
System.out.println(num + " " + numerator + "/" + denominator); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment