码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode 166] Fraction to Recurring Decimal

时间:2015-08-02 16:46:27      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:

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)".
    public class Solution {
        public String fractionToDecimal(int numerator, int denominator) {
            //注意正负
            //注意越界(转为long)
            //使用map记录余数和位置,当发现相同的余数时,则表示此余数对应位置的商位开始循环,此时需要用()包装
            //seq表示商
            long num=Math.abs((long)numerator);
            long deno=Math.abs((long)denominator);
            int flag=1;
            if(numerator>0&&denominator<0||numerator<0&&denominator>0) flag=0;
            long s=num/deno;
            long t=num%deno;
            String res=flag==0?"-"+Long.toString(s):Long.toString(s);
            if(t==0) return res;
            else return res+"."+getRes(t,deno);
            
        }
        public StringBuilder getRes(long t,long deno){
            StringBuilder seq=new StringBuilder();
            HashMap<Long,Integer> map=new HashMap<Long,Integer>();
            int i=0;
            while(t!=0&&!map.containsKey(t)){
                map.put(t,i);
                i++;
                t*=10;
                seq.append(Long.toString(t/deno));
                t%=deno;
                
            }
            if(t!=0){
                seq.insert((int)map.get(t),‘(‘);
                seq.append(‘)‘);
            }
            return seq;
        }
    }

     

[leedcode 166] Fraction to Recurring Decimal

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4695915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!