2015年10月14日星期三

Fraction to Recurring Decimal leetcode

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".

用hashmap来记录余数, value存余数所得的商的位置, 当余数重复出现时候就能找到循环的数字的范围了
为了防止溢出要用long, 对于abs一定要取long得abs, 因为abs(Integer.MIN_VALUE)是他本身
public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0 || denominator == 0) {
            return "0";
        }
        
        String res = "";
        if ((numerator < 0 & denominator > 0) || (numerator > 0 && denominator < 0)) {
            res += "-";
        }
        long num = numerator, den = denominator;
        num = Math.abs(num);
        den = Math.abs(den);
        long ans = num / den;
        long rem = (num % den) * 10;
        res += ans;
        if (rem == 0) {
            return res;
        }
        res += ".";
        HashMap<Long, Integer> map = new HashMap<Long, Integer>();
        while (rem != 0) {
            if (map.containsKey(rem)) {
                int index = map.get(rem);
                String part1 = res.substring(0, index);
                String part2 = res.substring(index, res.length());
                res = part1 + "(" +part2 + ")";
                return res;
            } else {
                map.put(rem, res.length());
                res += rem / den;
                rem = rem % den * 10;
            }
        }
        return res;
        
    }
}

没有评论:

发表评论