DEV Community

Seth
Seth

Posted on

String to integer aloi

Lets say the string we are given is '4123'. Lets's start by figuring out how we are going to get to that number itself.

This way is cheeky.

  1. When we look at any number we can do the first number times 10 plus then 2nd number. In this case
((4 * 10 + 1)* 10 + 2) * 10 + 3)
________
  {41}
((4 * 10 + 1)* 10 + 2) * 10 + 3)
________________
  {410}
((4 * 10 + 1)* 10 + 2) * 10 + 3)
______________________
        {412}
((4 * 10 + 1)* 10 + 2) * 10 + 3)
_________________________________
                   {4123)
Enter fullscreen mode Exit fullscreen mode

Every time we multiply the number by ten we get a 0 in place that we can then change using addition. We keep adding numbers to the right hand side each iteration until we've got the entire number.

Another way to look at it is this.

41 ->
410 -> 
 +12 ->
____
412. 
*10 ->
4120
  +3 ->
____
4123
Enter fullscreen mode Exit fullscreen mode

Now, let's get into how we're going to solve this problem. It's very simple with the code, and you'll be kicking yourself if you've been struggling with it once you see it.

1) turn the str into a number with parseInt method
2) if the number isn't a number, return 0
3) if the number is less then the lower bound, return the lower bound
4) if the number is greater the the higher bound, return the higher bound
5) if we don't hit any of these condition return the parseInt'd number

const aloi = (str) => {
 let num = parseInt(str) 
 if (Number.isNaN(num)){
 return 0
}
 if (num < -2**31) {
 return -2**31
}
 if (num > 2**31-1) {
 return 2**31-1
}
 return num
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)