If you're faced with an input box, like this:
+--------------+
Enter the price of the item, in dolla...
For further actions, you may consider blocking this person and/or reporting abuse
This is my solution in Python3
EDIT: Removed space, thanks for correcting me guys
This was great, but failed (Python 3.8) the first test due to the added space - added an additional replace and passed all tests.
You could also use the method
strip
strip
doc:This doesn't work with string = "-$ 0.1" isn't it? I'd rather prefer the replace way :P
Thank you!
you alse need to remove space from the string to avoid the exception
This is my solution in javascript:
A more readable version:
My solution in Typescript
I like this but I will do it without /g as you will encounter this replacement at the most once. Also space after $ maybe present or may not be so
/\$?\s?/
would do I guess. What do you think?In C with O(1):
Is
atof
O(1)?Well, technically
atof
is O(n), but while specifing the big O notation, I just abstracted all the library calls to O(1). And I think that doing this is the most stupid thing but it just helps me to analyse what could be the worst case scenario of my implementation. Hope it doesn't mislead any wrong information.Here's Kotlin with a String extension function:
Ruby
APL (using Dyalog APL):
(Use the bookmarklet on this post to see the code with APL font and syntax highlighting.)
Removes the characters
$
and space using "set difference"~
, and evaluates⍎
the resulting string as APL expression. The preceding-
gets evaluated as the "negate" function, and APL's numeric notation uses¯
(read "high minus") for the negative sign.This was my solution typescript/javascript
Here is the simple solution with Python:
Using the
while
loop andif...else
conditions to check specific string pattern and replace unwanted character.Then return
s
with casting to float value finally.solution in js
Javascript
fails on negative values, due to replacing the '-'