Skip to content

Commit 03fe625

Browse files
committed
tricky question on parseint
1 parent ea5d305 commit 03fe625

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Javascript/Tricky-JS-Problems/Collection-of-Tricky-JS-Questlions.md

+29
Original file line numberDiff line numberDiff line change
@@ -321,3 +321,32 @@ Here's the sequence of events:
321321
- `parseInt` ignores the remainder of the string, since it can't be converted.
322322

323323
Note that you'd get a result for any base `>= 19`, but not for bases below that. For bases `>= 24`, you'll get a larger result, as `n` becomes a valid digit at that point.
324+
325+
### Explanation-3
326+
327+
To add to the above answers
328+
329+
`parseInt(1/0,19)` is equivalent to `parseInt("Infinity",19)`
330+
331+
Within base 19 numbers `0-9` and `A-I` `(or a-i)` are a valid numbers. So, from the "Infinity" it takes `I` of base 19 and converts to base 10 which becomes 18
332+
Then it tries to take the next character i.e. `n` which is not present in base 19 so discards next characters (as per javascript's behavior of converting string to number)
333+
334+
So, if you write `parseInt("Infinity",19)` OR `parseInt("I",19)` OR `parseInt("i",19)` the result will be same i.e `18`.
335+
336+
Now, if you write `parseInt("I0",19)` the result will be `342`
337+
as `I X 19 (the base)^1 + 0 X 19^0` = `18 X 19^1 + 0 X 19^0` = `18 X 19 + 0 X 1` = `342`
338+
339+
Similarly, `parseInt("I11",19)` will result in `6518`
340+
341+
i.e.
342+
343+
```
344+
18 X 19^2 + 1 X 19^1 + 1 X 19^0
345+
= 18 X 19^2 + 1 X 19^1 + 1 X 19^0
346+
= 18 X 361 + 1 X 19 + 1 X 1
347+
= 6498 + 19 + 1
348+
= 6518
349+
350+
```
351+
352+
---

0 commit comments

Comments
 (0)