📣 Calling experienced devs and recent interviewees! Join the "Coding Problem Interview Series" to help code newbies tackle interview questions asse...
For further actions, you may consider blocking this person and/or reporting abuse
Troll answer (JS):
I think this needs a few self-imposed rules, such as not using any built-in language features or APIs to do the conversion.
lol. let me do all your work in a single line:
function atoi(str) {
return +str
}
@urielbitton I still prefer my one-liner
const atoi = parseInt
, because+str
doesn't fulfil the spec (might return a non-integer) 😉True,
+'...'
behaves similar toNumber
, so it'll convert floats as well.@lionelrowe + quite literally replaces parseInt in 99% or perhaps 100% of cases in javascript.
Not if you only want integers...
@urielbitton It depends what your use case is. I usually use
Number(str)
instead of+str
as it's more explicit, plus it can be passed as a callback to array functions (['1', '2', '3'].map(Number) => [1, 2, 3]
). I usually only useparseInt
if I want to parse in a radix other than 10, e.g. parsing hex strings (parseInt('ff', 16) => 255
), or if I want the result to be truncated (parseInt('16.9')
). And I use=> 16
parseFloat
where I want to ignore a unit at the end, e.g.parseFloat('99.9%') => 99.9
.just add .toFixed(0)
just add .toFixed(0) ...
OK, that potentially covers 1 of the 4 use cases I mentioned, but it doesn't even work, as
toFixed
converts it back to a string...Sure, you could re-convert to a number, but at that point you're degrading performance and complicating your code just to avoid using
parseInt
, a function that already exists natively in the language for that specific purpose.The second answer is somehow same idea with the first answer but then the first one is much cleaner and more efficient in any ways. Solution they are looking for is maybe to parse manually, taking care of the cases, char to integer… very basic.
This was really hard to type in an iPhone, but I am pretty sure this is good, and that it covers the most common foot-guns.
Nice! Needs a couple of changes though — the math isn't quite right for summing the digits, and the while loop doesn't terminate as
ptr
is never incremented:Thanks! I knew there was no way I nailed it first go on my iPhone.
Rust (be gentle, I'm learning 😅)
Elm + Parser combinators:
You begin with the
Integer
data structure.The
intP
parser is a recipe of how you can generate anInteger
instance from a raw string, step by step.Once you have filled all the holes of the data structure, you can then process it and generate the integer value (with the
applySign
function).The
atoi
function wraps the execution of the parser and returns theMaybe Int
value.This approach is closer to intermediate/advanced than to newbies, but this is how parsing is done in a functional style.
If you want to play with the exercise: ellie-app.com/nm6g8LCw37za1
I love reading Elm code even though I find it hard to understand, it's kinda brain-bending in a good way!
I noticed you're using
String.toInt
though, so you could replace the wholeatoi
implementation with that, as it already handles+
and-
:You are absolutely right!
String.toInt
already does the job. Wouldn't that be considered cheating during a job interview, though? :)Parser combinators are an extra brain-bending feature within the language. But it is so powerful that it's worth learning if you want to parse stuff and RegEx falls too short for the job.
JAVA
(still learning, so forgive my not so neat code😅)
Works perfectly, at least for well-formed input. For malformed input,
Solution#.myAtoi('abc123')
gives0
, andSolution#.myAtoi('123abc')
gives123
, which is a reasonable thing to do if you want parsing to be lenient (JS'sparseInt
works similarly, except it returnsNaN
instead of0
where the input begins with an unparseable char).I don't think it makes much sense to have
num
be adouble
and then cast it to anint
when returning it, though. To improve performance if nothing else, it'd be better to declare it as anint
, then you can remove all the type casts.The only possible drawback is that it changes the behavior for values that overflow the max int value: with purely int types, you get wrapping (2147483647 + 1 = -2147483648), whereas if using a double internally, you get saturation (2147483647 + 1 = 2147483647). I don't think either one is strictly more/less correct than the other, though.
Hey lionel,
I just copied the copied that I wrote for the same questions in leetcode.😅
My code is logically designed based on its demand and test cases.
var s = "2345";
var result = 1*s;
Works most of the time, but there are a few edge cases:
""
," "
are invalid inputs yet they return0
There is a lot of invalid inputs ("aaa", "baa", etc). You must know what you do.
But "" and " " are VALID inputs, because it returns valid answer - 0.
Hey Vladas, sorry I wasn't clear enough in my response.
Let me illustrate my point:
Cheers!
It must be an internal parser which just skips initial blanks, and it's initialized to 0.
I would program exactly the same.
JS / TS Shorthand I only discovered more recently than I'm willing to admit
Perl had something that some referred to as the Venus operator,
0+
. Very clever stuff.