Leetcode 166 Fraction to Recurring Decimal

HowieLee59發表於2019-01-15

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.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"

這個題是簡單的字串處理,題意就是進行一個除運算,如果說有迴圈出現的數出現的話,那麼用()闊起來。

class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        long a = numerator,b = denominator,m = a % b;//使用long型別擴大涉及的範圍
        Map<Long,Integer> map = new HashMap<Long,Integer>();//用來儲存小數的位置
        if(m == 0){
            return a / b + "";
        }
        StringBuilder sc = new StringBuilder();
        if(a * b < 0){
            sc.append('-');//留意負數的情況
        }
        a = Math.abs(a);
        b = Math.abs(b);
        sc.append(a / b).append('.');
        long c = a / b;
        a -= b * c;
        m = a % b;
        map.put(m,sc.length());
        while(m != 0){
            a *= 10;
            sc.append(a / b);
            m = a % b;
            c = a / b;
            a -= b * c;
            if(map.containsKey(m)){
                return sc.insert((int)map.get(m),'(').append(')').toString();
            }//在小數出現之前和之後分別插入'('和')'
            map.put(m,sc.length());
        }
        return sc.toString();
    }
}

主要應該注意的就是字串的處理部分

相關文章