Short Java solution


  • 56
    T
    public String fractionToDecimal(int numerator, int denominator) {
        StringBuilder result = new StringBuilder();
        String sign = (numerator < 0 == denominator < 0 || numerator == 0) ? "" : "-";
        long num = Math.abs((long) numerator);
        long den = Math.abs((long) denominator);
        result.append(sign);
        result.append(num / den);
        long remainder = num % den;
        if (remainder == 0)
            return result.toString();
        result.append(".");
        HashMap<Long, Integer> hashMap = new HashMap<Long, Integer>();
        while (!hashMap.containsKey(remainder)) {
            hashMap.put(remainder, result.length());
            result.append(10 * remainder / den);
            remainder = 10 * remainder % den;
        }
        int index = hashMap.get(remainder);
        result.insert(index, "(");
        result.append(")");
        return result.toString().replace("(0)", "");
    }

  • 0
    A

    Nice answer, well done! Quite a nice way to think about the problem.


  • 0
    Y

    (numerator < 0 == denominator < 0 || numerator == 0) ? "" : "-", Can you explain a bit of this line. I don't quite understand the first part( numerator < 0 == denominator < 0), especially what does "==" mean. I think "==" should mean equal. So how do you decide the sign with this line. Thanks


  • 0
    G

    If the numerator and denominator have the same sign, like -1 and -2. It will be "true == true" which is true which gives a result of "". Otherwise it will be false (like false == true) which gives a result of "-" as the sign


  • 0
    Y

    Thx! First time saw this kind of expression. Smart way!


  • 0
    W

    Can you help me explain why we should change int to long ?


  • 0

    @www2277843987 Consider the numerator is Integer.MIN_VALUE. Math.abs((long) numerator) is 2147483648, while Math.abs(numerator) is -2147483648.


  • 1
    C

    said in Short Java solution:

    numerator < 0 == denominator < 0 || numerator == 0

    This is kind of confusing at first glance and makes people who are not familiar with operator precedence feel lost. Maybe u should use

    numerator < 0 ^ denominator < 0
    

  • 0
    R

    @celestial
    when
    numerator and denominator have same sign or numerator is 0,
    sign is +
    otherwise
    sign is -


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.