题目:
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)".
链接: http://leetcode.com/problems/fraction-to-recurring-decimal/
看别人都是转换为long再计算,不想做,有本事你让所有题都不考虑边界条件啊?谁出的这道题谁傻x
官方解答
https://leetcode.com/articles/fraction-recurring-decimal/
更多讨论
https://discuss.leetcode.com/category/174/fraction-to-recurring-decimal
我的错误的答案,跑不过-1 -2147483648
1 public class Solution { 2 public String fractionToDecimal(int numerator, int denominator) { 3 if (denominator == 0) { 4 return ""; 5 } 6 7 int integer = numerator / denominator; 8 int remaining = numerator % denominator; 9 if (remaining == 0) { 10 return Integer.toString(integer); 11 } 12 13 StringBuilder result = new StringBuilder(); 14 if (numerator > 0 && denominator < 0 || numerator < 0 && denominator > 0) { 15 result.append("-"); 16 remaining = -remaining; 17 } 18 result.append(Integer.toString(Math.abs(integer))); 19 result.append("."); 20 21 Map<Integer, Integer> fractionalPositions = new HashMap<Integer, Integer>(); 22 List<Integer> fractionals = new ArrayList<Integer>(); 23 int curPos = 0; 24 fractionalPositions.put(remaining, curPos); 25 curPos++; 26 27 while (remaining != 0) { 28 remaining *= 10; 29 fractionals.add(remaining / denominator); 30 remaining %= denominator; 31 if (fractionalPositions.containsKey(remaining)) { 32 int pos = fractionalPositions.get(remaining); 33 // build fractional part string 34 for (int i = 0; i < fractionals.size(); i++) { 35 if (i == pos) { 36 result.append("("); 37 } 38 result.append(Integer.toString(fractionals.get(i))); 39 } 40 result.append(")"); 41 break; 42 } else { 43 fractionalPositions.put(remaining, curPos); 44 } 45 curPos++; 46 } 47 if (remaining == 0) { 48 for (int i = 0; i < fractionals.size(); i++) { 49 result.append(Integer.toString(fractionals.get(i))); 50 } 51 } 52 return result.toString(); 53 } 54 }