Simplified Fractions 之 判断最简分数
1.判断最简分数gcd函数
class Solution { public List<String> simplifiedFractions(int n) { List<String> res = new ArrayList<>(); for(int molecule = 1; molecule < n; molecule++){ for(int denominator = molecule+1; denominator <= n; denominator++){ if(gcd(molecule, denominator) == 1){ String cur = molecule + "/" + denominator; res.add(cur); } } } return res; } //判断是否为最简分数 private int gcd(int x, int y){ return x == 0 ? y : gcd(y % x, x); } }
2.将分数转成另一个double变量,判断是否在set中。
class Solution { public List<String> simplifiedFractions(int n) { List<String> res = new ArrayList<>(); Set<Double> set = new HashSet<>(); for(int molecule = 1; molecule < n; molecule++){ for(int denominator = molecule+1; denominator <= n; denominator++){ if(set.add((double)molecule / denominator)){//判断是否为最简分数 String cur = molecule + "/" + denominator; res.add(cur); } } } return res; } }