leetcode--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)".
[java]  view plain  copy
  1. public class Solution {  
  2.     public String fractionToDecimal(int numerator, int denominator) {  
  3.         if(numerator==0return "0";  
  4.         if(denominator==0return "";  
  5.         String res="";  
  6.         if((numerator<0)^(denominator<0)) res+="-";  
  7.         long num = numerator;  
  8.         long den = denominator;  
  9.         num = Math.abs(num);  
  10.         den = Math.abs(den);  
  11.         long ans = num/den;  
  12.         res += ans;  
  13.         if(num%den==0return res;  
  14.         else res+=".";  
  15.           
  16.         long t = num%den*10;  
  17.         System.out.println(den);  
  18.         Map<Long,Integer> map = new HashMap<Long,Integer>();  
  19.         while(t>0){  
  20.             if(map.containsKey(t)){  
  21.                 int mid = map.get(t);  
  22.                 String part1 = res.substring(0, mid);    
  23.                 String part2 = res.substring(mid, res.length());    
  24.                 res = part1 + "(" + part2 + ")";    
  25.                 return res;  
  26.             }  
  27.             map.put(t, res.length());  
  28.             ans = t/den;  
  29.             System.out.println(ans);  
  30.             res += String.valueOf(ans);  
  31.             t = (t%den)*10;  
  32.         }  
  33.         return res;  
  34.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46573617

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值