http://www.1point3acres.com/bbs/thread-142376-1-1.html
设计一个fraction number 的class,要求实现equals和String toDecimal()。
toDecimal是leetcode原题,equals的话注意先得到gcd,然后除了之后再比较。还有分子分母是否为0,符号不一样等等都需要考虑。细节挺多的。
https://github.com/openmrs/openmrs-module-reporting/blob/master/api/src/main/java/org/openmrs/module/reporting/common/Fraction.java| public class Fraction extends Number implements Comparable<Fraction>, Serializable { | |
| public static final long serialVersionUID = 1L; | |
| private final int numerator; | |
| private final int denominator; | |
| public Fraction(int numerator, int denominator) { | |
| this.numerator = numerator; | |
| this.denominator = denominator; | |
| } | |
| /** | |
| * @should return the greatest common divisor between 2 numbers | |
| */ | |
| public static int gcd(int n1, int n2) { | |
| if (n2 == 0) { return n1; } | |
| return gcd(n2, n1 % n2); | |
| } | |
| /** | |
| * @should return a new fraction reduced to lowest form | |
| */ | |
| public Fraction reduce() { | |
| int gcd = gcd(numerator, denominator); | |
| return new Fraction((int)numerator/gcd, (int)denominator/gcd); | |
| } | |
| /** | |
| * @param decimalPlaces the number of decimal points to include | |
| * @return this Fraction formatted as a percentage | |
| * @should return a percentage to the correct precision | |
| */ | |
| public String toPercentString(int decimalPlaces) { | |
| if (denominator == 0) { return "N/A"; } | |
| NumberFormat nf = NumberFormat.getPercentInstance(); | |
| nf.setMaximumFractionDigits(decimalPlaces); | |
| return nf.format(doubleValue()); | |
| } | |
| public int compareTo(Fraction that) { | |
| long n1 = this.numerator * that.denominator; | |
| long n2 = this.denominator * that.numerator; | |
| return ((n1 < n2) ? -1 : (n1 > n2 ? 1 : 0)); | |
| } | |
| @Override | |
| public boolean equals(Object that) { | |
| if (this == that) { return true; } | |
| if (that != null && that instanceof Fraction) { | |
| return this.compareTo((Fraction)that) == 0; | |
| } | |
| return false; | |
| } | |
| @Override | |
| public int hashCode() { | |
| Fraction f = this.reduce(); | |
| return 31 * (31 * 7 + f.getNumerator()) + f.getDenominator(); | |
| } | |
| @Override | |
| public String toString() { | |
| return toPercentString(1) + " (" + numerator + " / " + denominator + ")"; | |
| } | |
| } |