Leet Code Solution 8 - String to Integer (atoi)

Updated on

DISCLAIMER: Expressed views on this blog are my own.

String to Integer (atoi), Medium

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.


The algorithm for myAtoi(string s) is as follows:


Whitespace: Ignore any leading whitespace (" ").

Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present.

Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.

Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.

Return the integer as the final result.

Solution, Typescript

function myAtoi(s: string): number {
s = s.trim(); // remove whitespace

let sign = 1;
let startIdx = 0;
let endIdx = s.length - 1;

// detect signedneess
if(s.charAt(0) === "-") {
sign = -1;
startIdx++;
} else if(s.charAt(0) === "+") {
startIdx++;
}

// skip leading zeros
while(true) {
if(s.charAt(startIdx) !== "0") {
break
}
startIdx++;
}

let val = 0;
let placeVal = 1;
for(let i = endIdx; i >= startIdx; i--) {

let digit = digitConvert(s.charAt(i));
if(digit == -1) {
val = 0;
placeVal = 1;
continue;
}
val += digit * placeVal;
placeVal *= 10;
}

val = sign*val;

// console.log(val)
val = Math.max(val, -(2**31));
// console.log(val, (-2)**31)
val = Math.min(val, 2**31 - 1);
// console.log(val, 2**31 - 1)

return val;
};

function digitConvert(s: string): number {
switch(s) {
case "0":
return 0;
case "1":
return 1;
case "2":
return 2;
case "3":
return 3;
case "4":
return 4;
case "5":
return 5;
case "6":
return 6;
case "7":
return 7;
case "8":
return 8;
case "9":
return 9;
default:
return -1;
}
You just read "Leet Code Solution 8 - String to Integer (atoi)". Please share if you liked it!
You can read more recent posts here.