IncredibleThings

导航

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

 

这题的解题思路是模拟除法的过程,然后用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();
            
        }
    }
}

 

posted on 2015-03-06 10:18  IncredibleThings  阅读(200)  评论(0编辑  收藏  举报