Skip to content

2117. Abbreviating the Product of a Range 👎

  • Time: $O(\texttt{right} - \texttt{left})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
 public:
  string abbreviateProduct(int left, int right) {
    constexpr long long maxSuf = 1000000000000;
    double prod = 1.0;
    long long suf = 1;
    int countDigits = 0;
    int countZeros = 0;

    for (int num = left; num <= right; ++num) {
      prod *= num;
      while (prod >= 1.0) {
        prod /= 10;
        ++countDigits;
      }
      suf *= num;
      while (suf % 10 == 0) {
        suf /= 10;
        ++countZeros;
      }
      if (suf > maxSuf)
        suf %= maxSuf;
    }

    if (countDigits - countZeros <= 10) {
      const long tens = pow(10, countDigits - countZeros);
      return to_string(static_cast<long>(prod * tens + 0.5)) + 'e' +
             to_string(countZeros);
    }

    const string pre = to_string((long)(prod * pow(10, 5)));
    string sufStr = to_string(suf);
    sufStr = sufStr.substr(sufStr.length() - 5);
    return pre + "..." + sufStr + 'e' + to_string(countZeros);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
  public String abbreviateProduct(int left, int right) {
    final long maxSuf = 100000000000L;
    double prod = 1.0;
    long suf = 1;
    int countDigits = 0;
    int countZeros = 0;

    for (int num = left; num <= right; ++num) {
      prod *= num;
      while (prod >= 1.0) {
        prod /= 10;
        ++countDigits;
      }
      suf *= num;
      while (suf % 10 == 0) {
        suf /= 10;
        ++countZeros;
      }
      if (suf > maxSuf)
        suf %= maxSuf;
    }

    if (countDigits - countZeros <= 10) {
      final long tens = (long) Math.pow(10, countDigits - countZeros);
      return String.valueOf((long) (prod * tens + 0.5)) + "e" + String.valueOf(countZeros);
    }

    final String pre = String.valueOf((long) (prd * Math.pow(10, 5)));
    String sufStr = String.valueOf(suf);
    sufStr = sufStr.substring(sufStr.length() - 5);
    return pre + "..." + sufStr + "e" + String.valueOf(countZeros);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
  def abbreviateProduct(self, left: int, right: int) -> str:
    prod = 1.0
    suf = 1
    countDigits = 0
    countZeros = 0

    for num in range(left, right + 1):
      prod *= num
      while prod >= 1.0:
        prod /= 10
        countDigits += 1
      suf *= num
      while suf % 10 == 0:
        suf //= 10
        countZeros += 1
      if suf > 10 ** 8:
        suf %= 10 ** 8

    if countDigits - countZeros <= 10:
      tens = 10 ** (countDigits - countZeros)
      return str(int(prod * tens + 0.5)) + 'e' + str(countZeros)

    pre = str(int(prod * 10 ** 5))
    suf = str(suf)[-5:]
    return pre + '...' + suf + 'e' + str(countZeros)