zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    HBase 列族数量为什么越少越好
    Hbase 认识及其作用
    Hbase 源码讲解
    Hbase 目录树
    rabbitmq 连接过程详解
    rabbit 兔子和兔子窝
    rabbit 函数参数详解
    rabbitmq 用户和授权
    火狐浏览器安装有道插件
    rabbitmq vhost
  • 原文地址:https://www.cnblogs.com/yawenw/p/13042184.html
Copyright © 2011-2022 走看看