166. Fraction to Recurring Decimal

来源:互联网 发布:日军轰炸重庆 知乎 编辑:程序博客网 时间:2024/05/17 19:21

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)".

Hint:

  1. No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
  2. Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
  3. Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
Because the ace rate is really low so I put some test cases below the solution.
Solution
public static String fractionToDecimal2(int numerator, int denominator) {if(numerator == 0){            return "0";        }        StringBuilder sb = new StringBuilder();        sb.append(((numerator < 0) ^ (denominator < 0)) ? "-" : "");        long num = Math.abs((long)numerator);// consider integer overflow        long den = Math.abs((long)denominator);        sb.append(num / den);        if(num % den == 0){            return sb.toString();        }        sb.append(".");                Map<String, Integer> map = new HashMap<String, Integer>();        long remain = num % den;        map.put(remain + "", sb.length());        while(remain != 0){        remain = remain * 10;        sb.append(remain / den);        remain = remain % den;            if(map.containsKey(remain + "")){                int index = map.get(remain + "");                sb.insert(index, "(");                sb.append(")");                break;            }else{                 map.put(remain + "", sb.length());            }        }           return sb.toString();    }public static void main(String[] args) {System.out.println(fractionToDecimal2(1, 6));System.out.println(fractionToDecimal2(4, 7));System.out.println(fractionToDecimal2(-50, 8));System.out.println(fractionToDecimal2(-1, -2147483648));}


0 0