[Leetcode] 8. String to Integer (atoi)

Seongjun Lee·2022년 2월 19일
0

[Leetcode] - Problem

목록 보기
8/43
post-thumbnail

Problem

문제 링크

C 언어의 atoi를 구현하는 문제

Solution

정규식을 이용하여 부호(+,-)와 숫자만 가지고온다. 그리고 정규식으로 값을 찾지 못했을때 0을 가지는 배열을 반납하도록한다.
integer 범위 조건을 처리를하고 범위를 벗어나지않으면 그대로 리턴한다

JS Code

/**
 * @param {string} s
 * @return {number}
 */
var myAtoi = function(s) {
  
  s = s.trim().match(/^[-+]?\d+/) || [0]
  s = s[0]
  
  if (!s) return 0
  if (parseInt(s) < -Math.pow(2,31)) return -Math.pow(2,31)
  else if(Math.pow(2,31)-1 < parseInt(s)) return Math.pow(2,31)-1
  else return parseInt(s)
}
profile
Hi there 👋

0개의 댓글