`
hcx2013
  • 浏览: 83027 次
社区版块
存档分类
最新评论

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.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".
import java.util.HashMap;

public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
        	return new String("0");
        }
        boolean flag = (numerator > 0) ^ (denominator > 0);
        long Numerator = Math.abs((long)numerator);
        long Denominator = Math.abs((long)denominator);
        StringBuffer res = new StringBuffer();
        if (flag == true) {
        	res.append("-");
        }
        res.append((Numerator / Denominator));
        Numerator = Numerator % Denominator;
        if (Numerator == 0) {
        	return res.toString();
        }
        res.append(".");
        HashMap<Long,Integer> hashMap = new HashMap<>();
        for (int i = res.length(); Numerator != 0; i++) {
			if (hashMap.get(Numerator) != null) {
				break;
			}
			hashMap.put(Numerator, i);
			Numerator *= 10;
			res.append(Numerator / Denominator);
			Numerator = Numerator % Denominator;
		}
        if (Numerator == 0) {
        	return res.toString();
        }
        res.insert(hashMap.get(Numerator), "(");
        res.append(")");
        return res.toString();
    }
}

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics