Google面试题:M-Fraction to Recurring Decimal

30 篇文章 0 订阅
4 篇文章 0 订阅

http://www.jiuzhang.com/article/Google2014Experience%20%E8%BD%AF%E4%BB%B6%E5%B7%A5%E7%A8%8B%E5%B8%88onsite%EF%BC%883%EF%BC%89/

http://www.lintcode.com/zh-cn/problem/add-operators/


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)".

Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.


class Solution {
        public String fractionToDecimal(int numerator, int denominator) {
    	
		if(numerator==0) return "0";
		if(denominator==0) return "";
		
		long a = numerator, b = denominator;
		a = Math.abs(a);
		b = Math.abs(b);
//		//直接转abs会溢出
//		long a = Math.abs(numerator);
//		long b = Math.abs(denominator);
		
        StringBuffer res = new StringBuffer("");
        if ((numerator < 0) ^ (denominator < 0)){
            res.append("-");
        }
		
		long pre = a/b;
		res.append(pre);		
		long rem = (a%b)*10;
		if(rem==0) return res.toString();
		
		Map<Long, Integer> map = new HashMap<Long, Integer>();
		res.append(".");
		while(rem!=0){
			//已经出现过该余数,最后的过程相同可定得到相同的循环
			if(map.containsKey(rem)){
				int bei = map.get(rem);
				return res.substring(0, bei)+"("+res.substring(bei, res.length())+")";
			}
			
			//没有出现过该余数
			map.put(rem, res.length());
			pre = rem/b;
			res.append(pre);
			rem = (rem%b)*10;
		}
		return res.toString();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值