1
public String fractionToDecimal(int numerator, int denominator) {
    if (numerator==0)
        return "0";
    long a = numerator,b = denominator;
    StringBuilder ans = new StringBuilder();
    if (a*b<0)
        ans.append('-');
    a=Math.abs(a);
    b=Math.abs(b);
    ans.append(a/b);
    if (a%b==0)
        return ans.toString();
    ans.append('.');
    Map<Long,Integer> flag = new HashMap<>();
    while ((a=(a%b)*10)!=0&&!flag.containsKey(a)){
        flag.put(a,ans.length());
        ans.append(a/b);
    }
    if (a%b==0)
        return ans.toString();
    return ans.insert(flag.get(a),'(').append(")").toString();
}

This is the code in question. An error message appears in the last returnenter image description hereIf you use the intvalue method after get (a), there will be no compilation error, or if you change the following char type to string "(", there will be no error. Why?

samabcde
  • 6,988
  • 2
  • 25
  • 41
  • I think it's because `insert` has many overloads (see https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html), and you are passing `(Long, char`)` in the code above. There isn't an exact match, so it doesn't know which applies. If you do either of your workarounds, then it's no longer ambiguous. – user2740650 Oct 10 '21 at 13:48

0 Answers0