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

LeetCode-Fraction to Recurring Decimal

时间:2015-03-06 10:29:22      阅读:164      评论: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)"

 

这题的解题思路是模拟除法的过程,然后用hashMap存储每一步所得出的余数,和所要输出结果的当前length。

需要注意的是极限情况下,例如最小的负int值,在转换成正数时,是溢出int的,故得需要用long值去handle输入值。

另外 insert方法也得注意。

public class Solution {

    public String fractionToDecimal(int numerator, int denominator){
        if(numerator==0){
            return "0";
        }
        
        long num = Math.abs((long)numerator);
        long den = Math.abs((long) denominator);
        
        StringBuilder res = new StringBuilder();
        HashMap<Long, Integer> container = new HashMap();
        boolean isNegative=false;
        if(numerator < 0){
            isNegative = !isNegative;
        }
        
        if(denominator<0){
            isNegative = !isNegative;
        }
        
        if(isNegative){
            res.append(‘-‘);
        }
        
        long reminder = num%den;
        res.append(num/den);    
        int size = res.length();
        boolean hasCycle = false;
        while(reminder != 0 ){
            if(container.isEmpty()){
                res.append(‘.‘);
                size++;
            }
            if(!container.containsKey(reminder)){
                size++;
                long newQuoient = reminder*10/den;
                res.append(newQuoient);
                container.put(reminder,size);
                reminder = reminder*10%den;
            }
            else{
                hasCycle = true;
                break;
            }
        }
        
        if(!hasCycle){
            return res.toString();
        }
        else{
            res.insert(container.get(reminder)-1, "(");
            res.append(‘)‘);
            return res.toString();
            
        }
    }
}

 

LeetCode-Fraction to Recurring Decimal

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4317410.html

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