[LeetCode] Abbreviating the Product of a Range

2117. Abbreviating the Product of a Range

You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right].

Since the product may be very large, you will abbreviate it following these steps:

    1. Count all trailing zeros in the product and remove them. Let us denote this count as C.
  • For example, there are 3 trailing zeros in 1000, and there are 0 trailing zeros in 546.
    1. Denote the remaining number of digits in the product as d. If d > 10, then express the product as <pre>...<suf> where <pre> denotes the first 5 digits of the product, and <suf>denotes the last 5 digits of the product after removing all trailing zeros. If d <= 10, we keep it unchanged.
  • For example, we express 1234567654321 as 12345…54321, but 1234567 is represented as 1234567.
    1. Finally, represent the product as a string "<pre>...<suf>eC".
  • For example, 12345678987600000 will be represented as “12345…89876e5”.

Return a string denoting the abbreviated product of all integers in the inclusive range [left, right].

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 {
public:
string abbreviateProduct(int left, int right) {
long long suf = 1, POW = 10000000000;
double pre = 1.0;
int zero = 0, remove = 0;
for(int i = left; i <= right; i++) {
suf *= i;
pre *= i;
while(pre >= 1.0) {
pre /= 10.0;
remove++;
}
while(!(suf % 10)) {
suf /= 10;
zero++;
}
if(suf >= POW) suf %= POW;
}
if(remove - zero <= 10) {
return to_string((long) (pre * pow(10, remove - zero) + 0.5)) + 'e' + to_string(zero);
}
string ssuf = "0000" + to_string(suf);
return to_string((long) (pre * pow(10, 5))) + "..." + ssuf.substr(ssuf.length() - 5) + 'e' + to_string(zero);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/31/PS/LeetCode/abbreviating-the-product-of-a-range/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.