Skip to content

Commit b5f9bdc

Browse files
authored
Create abbreviating-the-product-of-a-range.py
1 parent b50a392 commit b5f9bdc

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(r - l)
2+
# Space: O(1)
3+
4+
import math
5+
6+
7+
class Solution(object):
8+
def abbreviateProduct(self, left, right):
9+
"""
10+
:type left: int
11+
:type right: int
12+
:rtype: str
13+
"""
14+
PREFIX_LEN = SUFFIX_LEN = 5
15+
MOD = 10**(PREFIX_LEN+SUFFIX_LEN)
16+
curr, zeros = 1, 0
17+
abbr = False
18+
for i in xrange(left, right+1):
19+
curr *= i
20+
while not curr%10:
21+
curr //= 10
22+
zeros += 1
23+
q, curr = divmod(curr, MOD)
24+
if q:
25+
abbr = True
26+
if not abbr:
27+
return '%se%s' % (curr, zeros)
28+
decimal = reduce(lambda x, y: (x+y)%1, (math.log10(i) for i in xrange(left, right+1)))
29+
prefix = str(int(10**(decimal+(PREFIX_LEN-1))))
30+
suffix = str(curr % 10**SUFFIX_LEN).zfill(SUFFIX_LEN)
31+
return '%s...%se%s' % (prefix, suffix, zeros)

0 commit comments

Comments
 (0)