Fraction to Recurring Decimal
问题:
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.
思路:
模拟除法
判断循环节的时候用hashtable
我的代码:
import java.util.Hashtable; public class Solution { public String fractionToDecimal(int numerator, int denominator) { if(denominator == 0 || numerator == 0 ) return "0"; int cnt = 0; if(numerator < 0) { cnt++; } if(denominator < 0) { cnt++; } long num = Math.abs((long)numerator); long den = Math.abs((long)denominator); StringBuffer left = new StringBuffer(); long remain = num%den; num /= den; left.append(num); if(remain == 0) { return cnt == 1 ? "-"+left.toString() : left.toString(); } StringBuffer right = new StringBuffer(); Hashtable<Long,Integer> ht = new Hashtable<Long,Integer>(); num = remain; ht.put(num, 0); int index = 1; while(num != 0) { num *= 10; remain = num%den; num /= den; right.append(num); if(ht.containsKey(remain)) { right.insert(ht.get(remain),"("); right.append(‘)‘); break; } ht.put(remain,index); num = remain; index++; } String rst = left.toString() + "." + right.toString(); return cnt == 1 ? "-"+rst : rst; } }
他人代码:
public class Solution { public String fractionToDecimal(int numerator, int denominator) { if (numerator == 0) { return "0"; } StringBuilder res = new StringBuilder(); // "+" or "-" res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : ""); long num = Math.abs((long)numerator); long den = Math.abs((long)denominator); // integral part res.append(num / den); num %= den; if (num == 0) { return res.toString(); } // fractional part res.append("."); HashMap<Long, Integer> map = new HashMap<Long, Integer>(); map.put(num, res.length()); while (num != 0) { num *= 10; res.append(num / den); num %= den; if (map.containsKey(num)) { int index = map.get(num); res.insert(index, "("); res.append(")"); break; } else { map.put(num, res.length()); } } return res.toString(); } }
学习之处:
原文:http://www.cnblogs.com/sunshisonghit/p/4371962.html