标签:
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,
这题的解题思路是模拟除法的过程,然后用hashMap存储每一步所得出的余数,和所要输出结果的当前length。
需要注意的是极限情况下,例如最小的负int值,在转换成正数时,是溢出int的,故得需要用long值去handle输入值。
另外 insert方法也得注意。
public class Solution { public String fractionToDecimal(int numerator, int denominator){ if(numerator==0){ return "0"; } long num = Math.abs((long)numerator); long den = Math.abs((long) denominator); StringBuilder res = new StringBuilder(); HashMap<Long, Integer> container = new HashMap(); boolean isNegative=false; if(numerator < 0){ isNegative = !isNegative; } if(denominator<0){ isNegative = !isNegative; } if(isNegative){ res.append(‘-‘); } long reminder = num%den; res.append(num/den); int size = res.length(); boolean hasCycle = false; while(reminder != 0 ){ if(container.isEmpty()){ res.append(‘.‘); size++; } if(!container.containsKey(reminder)){ size++; long newQuoient = reminder*10/den; res.append(newQuoient); container.put(reminder,size); reminder = reminder*10%den; } else{ hasCycle = true; break; } } if(!hasCycle){ return res.toString(); } else{ res.insert(container.get(reminder)-1, "("); res.append(‘)‘); return res.toString(); } } }
LeetCode-Fraction to Recurring Decimal
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4317410.html