Question

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

Thinking:

  • Method:
    • 在计算小数时,如果出现了相同的被除数就会出现无限循环。
    • 通过哈希表存储被除数,值是当前被除数出现的位置。
    • 要考虑int的临界状况。
class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if(denominator == 0) return "NaN";
        Map<Long, Integer> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        if(numerator > 0 && denominator < 0 || numerator < 0 && denominator > 0) sb.append('-');
        long aa = Math.abs((long)numerator);
        long bb = Math.abs((long)denominator);
        long digit = aa / bb;
        sb.append(digit);
        long remain = aa % bb;
        if(remain == 0) return sb.toString();
        sb.append(".");
        int count = 1;
        while(remain != 0 && !map.containsKey(remain *10)){
            remain *= 10;
            map.put(remain, count++);
            sb.append(Math.abs(remain / bb));
            remain %= bb;
        }
        if(remain != 0){
            sb.append(")");
            int val = map.get(remain * 10);
            String result = sb.toString();
            int index = result.indexOf('.');
            sb.insert(val + index, '(');
        }
        return sb.toString();
    }
}

二刷

  1. 注意int的上下限问题。
  2. 如何退出程序,返回结果:
    • 余数为0.
    • 余数不为零,但是余数已经出现过了。这说明会出现循环小数。
      class Solution {
       public String fractionToDecimal(int numerator, int denominator) {
        if(denominator == 0) return "NaN";
        Map<Long, Integer> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        if(numerator > 0 && denominator < 0 || numerator < 0 && denominator > 0) sb.append('-');
        long aa = Math.abs((long)numerator);
        long bb = Math.abs((long)denominator);
        long digit = aa / bb;
        sb.append(digit);
        long remain = aa % bb;
        if(remain == 0) return sb.toString();
        sb.append(".");
        int count = 1;
        while(remain != 0 && !map.containsKey(remain *10)){
            remain *= 10;
            map.put(remain, count++);
            sb.append(Math.abs(remain / bb));
            remain %= bb;
        }
        if(remain != 0){
            sb.append(")");
            int val = map.get(remain * 10);
            String result = sb.toString();
            int index = result.indexOf('.');
            sb.insert(val + index, '(');
        }
        return sb.toString();
       }
      }