Parse Integer with parseInt()
Write a JavaScript function that takes a string representation of a number and a radix (base), and returns the parsed integer using parseInt() with the radix parameter. The radix specifies the numeral system to use: 2 for binary, 8 for octal, 10 for decimal, 16 for hexadecimal.
The parseInt() function in JavaScript parses a string argument and returns an integer of the specified radix. The radix parameter is critical to specify because without it, parseInt() can produce unexpected results: strings starting with "0x" are parsed as hexadecimal, while others may be parsed as octal in older browsers. Always specifying the radix (typically 10) is a best practice.
Unlike Number() or unary + operator which convert the entire string, parseInt() parses until it encounters an invalid character and returns the integer parsed so far. This makes it useful for extracting numbers from strings with trailing non-numeric characters like "42px".
Time complexity is O(n) where n is the string length. The function ignores leading whitespace and stops at the first non-numeric character for the given radix. Returns NaN if the first non-whitespace character cannot be converted.
Edge cases include strings starting with non-numeric characters (returns NaN), empty strings (returns NaN), radix values outside the range 2-36 (returns NaN), and strings with leading zeros or whitespace.
Example Input & Output
Binary 1010 = 10
Stops at non-numeric
Decimal parse
Hexadecimal FF = 255
Octal 77 = 63
Algorithm Flow

Solution Approach
Best Answers
function solution(str, radix) {
return parseInt(str, radix);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
