The division operation consists of three important parts:
- Sign of the result.
- Component
- Decimal part
In addition, there are several angular cases where you need to consider the fact that Integer.MIN_VALUE larger than Integer.MAX_VALUE when comparing in absolute form.
For example: -2147483648/-1 cannot produce 2147483648 when dividing as integer types. The reason is simple. The type of the resulting type will be integer, and the maximum positive value that the variable of the integer type may contain is +2147483647
To mitigate this scenario, we must first convert the numerator and denominator into their long positive form. This gives us an integral part of the answer.
XOR of two numbers will have a sign bit as 1 only if they have opposite signs. This solves the first part ( sign of the result) of the problem.
For the decimal part, we can use the general division rule, that is, multiply the remainder by 10 and try again to divide and repeat. Write down the remainder that we have already encountered in order to prevent the loop from transitioning to unlimited iterations.
public String fractionToDecimal(int A, int B) { StringBuilder sb = new StringBuilder((A^B) < 0 ? "-" : ""); long a = Math.abs((long)A); long b = Math.abs((long)B); sb.append(Long.toString(a/b)); long rem = a % b; sb.append((rem != 0) ? "." : ""); Map<Long, Integer> remainderMap = new HashMap<>(); int pos = 0; while (rem != 0){ sb.append(Long.toString((rem*10)/b)); remainderMap.put(rem, pos++); rem = (rem*10) % b; if (remainderMap.containsKey(rem)){ String currNum[] = sb.toString().split("\\."); return currNum[0] + "." + currNum[1].substring(0, remainderMap.get(rem)) + "(" + currNum[1].substring(remainderMap.get(rem)) + ")"; } } if (sb.toString().equals("-0")) return "0"; return sb.toString(); }
Output Example:
source share