class Solution { public String fractionToDecimal(int numerator, int denominator) { if(numerator == 0) return "0"; //make variables long q = 0 , rem = 0 ; // quotient and remainder StringBuilder ans = new StringBuilder(); //store absolute values of numerator and denominator , negatives will be dealt later long num = Math.abs((long)numerator); long den = Math.abs((long)denominator); boolean neg = false; // to check if ans should be negative or +ve if(numerator<0 || denominator<0) neg = true; if(numerator<0 && denominator<0) neg = false; //HM to store remainder and index position of string to check if rem is repeated //and add brackets at index position and at the end of the string; HashMap<Long,Long> map = new HashMap<>(); q = num / den; rem = num % den; ans.append(q); if(rem == 0){ if(neg) ans.insert(0,"-"); return ans.toString(); } else{ ans.append("."); //adding decimal while(rem!= 0){ if( map.containsKey(rem)){ long pos = map.get(rem); ans.insert((int)pos,"("); ans.append(")"); break; } else{ map.put(rem ,(long)ans.length()); rem *= 10; q = rem / den; rem = rem % den; ans.append(q); } } } if(neg) ans.insert(0,"-"); return ans.toString(); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter