标签:leetcode
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,
public class Solution { public String fractionToDecimal(int numerator, int denominator) { if(numerator == 0) return "0"; StringBuilder sb = new StringBuilder(); if((numerator > 0) ^ (denominator > 0)) sb.append('-'); long num = Math.abs((long)numerator); long den = Math.abs((long)denominator); sb.append(num / den); if(num % den == 0) return sb.toString(); sb.append("."); Map<Long, Integer> map = new HashMap<>(); while(num != 0){ long remainder = num % den; if(!map.containsKey(remainder)){ map.put(remainder, sb.length()); remainder *= 10; sb.append(remainder / den); num = remainder % den; }else{ sb.insert(map.get(remainder), "("); sb.append(")"); break; } } return sb.toString(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
#leetcode#Fraction to Recurring Decimal
标签:leetcode
原文地址:http://blog.csdn.net/chibaoneliuliuni/article/details/46857475