DEV Community

Discussion on: Daily Challenge #163 - Significant Figures

Collapse
 
candidateplanet profile image
lusen / they / them 🏳️‍🌈🥑

in python

note: added the 11 and 1.1 test cases because the subtracting-from-both-ends solution can have edge cases around there

def sigfig(num):
  # ignore 0's on the far left
  ldx = 0
  while num[ldx] == '0' and ldx < len(num):
    ldx += 1

  # ignore 0's on the far right if no decimal place
  rdx = len(num) - 1
  if num.find('.') > 0:
    return (rdx - ldx) # the +1 from below is cancelled out by needing to subtract the '.'
  else:
    while num[rdx] == '0' and rdx > -1:
      rdx -= 1
    return (rdx - ldx) + 1

print(sigfig('11'), 2)
print(sigfig('1.1'), 2)
print(sigfig('1'), 1)
print(sigfig('003'), 1)
print(sigfig('3000'), 1)
print(sigfig('404'), 3)
print(sigfig('050030210'), 7)
print(sigfig('0.1'), 1)
print(sigfig('0.0'), 1)