首页 > 代码库 > Fraction to Recurring Decimal

Fraction to Recurring Decimal

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

 

这题很麻烦。

1。首先要判断符号, numberator 和 denominator 都是可正可负的。

2。numberator 要用long 否则会溢出。

3。每一次只能被减数*10,而且当没有出现小数点前,不会出现括号。所以先把整数部分和小数点全部输出,

 1 public class Solution { 2     public String fractionToDecimal(int numerator, int denominator) { 3         if(numerator == 0) return new String("0"); 4         StringBuilder sb = new StringBuilder(); 5         boolean o = (numerator < 0) ^ (denominator < 0); 6         if(o) sb.append("-"); 7         long a = Math.abs((long)numerator); 8         long b = Math.abs((long)denominator); 9         sb.append(String.valueOf(a / b));10         a = a % b;11         if(a == 0) return sb.toString();12         sb.append(".");13         HashMap<Long, Integer> map = new HashMap<Long, Integer>();14         for(int pos = sb.length(); a != 0; pos ++){15             a *= 10;16             if(map.containsKey(a)){17                 sb.insert(map.get(a), "(");18                 sb.append(")");19                 break;20             }21             sb.append((int)(a / b));22             map.put(a, pos);23             a = a % b;24         }25         return sb.toString();26     }27 }

 

Fraction to Recurring Decimal