166. Fraction to Recurring Decimal

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BigFatSheep/article/details/84009191

Description

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

Problem URL


Solution

给分子和分母,以String的形式返回结果。

We divide this problem into three part. If numerator == 0, return;

First,get sign, sign is the xor result of num and den’s sign, push it into string builder.

Second, get integer part, convert num and den to long, convert first and then use abs. sb.append(num / den), then let num % den, if num == 0 now, we don’t have decimal part, return.

Third part is decimal part. I first use a map to remember the position to insert a bracket for certain num, if it shows again, It means it is repeating, we should enclose it with a pair of bracket. like we learned how to divide a num, num * 10 then divide den which num != 0; If we meet used num, insert a “(” at its position then enclose it, break; or we just simply add new num to sb.

Code

class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0){
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        //get sign first, using xor, two same = false.
        sb.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
        
        //get Integer part, if it could be divided, return;
        long num = Math.abs((long)numerator);
        long den = Math.abs((long)denominator);
        sb.append(num / den);
        num %= den;
        if (num == 0){
            return sb.toString();
        }
        
        //get decimal part, map is used to find the "(" position in sb.
        sb.append(".");
        HashMap<Long, Integer> map = new HashMap<>();
        map.put(num, sb.length());
        while (num != 0){
            num *= 10;
            sb.append(num / den);
            num %= den;
            if (map.containsKey(num)){
                int index = map.get(num);
                sb.insert(index, "(");
                sb.append(")");
                break;
            }
            else{
                map.put(num, sb.length());
            }
        }
        return sb.toString();
    }
}

Time Complexity: O()
Space Complexity: O()


Review

猜你喜欢

转载自blog.csdn.net/BigFatSheep/article/details/84009191