본문 바로가기
LeetCode

[LeetCode] 8. String to Integer (atoi)

by JungSeung 2023. 10. 16.
728x90

https://leetcode.com/

Implement the myAtoi(string s) function, which converts a string to a

32-bit signed integer (similar to C/C++'s atoi function).

The algorithm for myAtoi(string s) is as follows:
1. Read in and ignore any leading whitespace.
2. Check if the next character (if not already at the end of the string) is ' - ' or ' + '. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2^31 should be clamped to -2^31, and integers greater than 2^31 - 1 should be clamped to 2^31 - 1 .
6. Return the integer as the final result.


Note:

  • Only the space character ' ' is considered a whitespace character.
  • Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

 

Example 1:

Input: s = "42"
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
         ^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "42" ("42" is read in)
           ^
The parsed integer is 42.
Since 42 is in the range [-2^31, 2^31 - 1], the final result is 42.

 

Example 2:

Input: s = "   -42"
Output: -42
Explanation:
Step 1: "   -42" (leading whitespace is read and ignored)
            ^
Step 2: "   -42" ('-' is read, so the result should be negative)
             ^
Step 3: "   -42" ("42" is read in)
               ^
The parsed integer is -42.Since -42 is in the range [-2^31, 2^31 - 1], the final result is -42.

 

Example 3:

Input: s = "4193 with words"
Output: 4193
Explanation:
Step 1: "4193 with words" (no characters read because there is no leading whitespace)
         ^
Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
             ^
The parsed integer is 4193.
Since 4193 is in the range [-2^31, 2^31 - 1], the final result is 4193.

 
Constraints:

  • 0 <= s.length <= 200
  • s consists of English letters (lower-case and upper-case), digits (0-9), '  ', ' + ', ' - ', and ' . '.

 

Code :

var myAtoi = function(s) {
    let sign = "+"; // 부호
    const numArr = []; // 숫자 담을 배열
    const max = Math.pow(2, 31) - 1; // MAX값
    const min = Math.pow(-2, 31); // MIN값
    let n = 0; // 최종 리턴값
    const noneSpace = s.trimStart().split(''); // 선행 공백 모두 제거, 배열로 변환
    if(noneSpace[0] === '+' || noneSpace[0] === '-'){
    	// 제일 앞에 부호가 있으면 저장한 뒤 제일 앞 삭제
        sign = noneSpace[0];
        noneSpace.shift();
    }
    for(let str of noneSpace){
    	// 배열 순회 숫자값 기록, 문자열 or 공백 만나면 반복문 탈출
        if(isNaN(Number(str)) || str === " "){
            break;
        } else {
            numArr.push(str);
        }
    }
    if(numArr.length === 0){
    	// 아무 값도 담기지 않았다 = 문자열 안에 숫자가 없다, n(0) 리턴
        return n;
    }
    // 부호 반영
    if(sign === "+"){
        n = Number(numArr.join(''));
        if(n >= max){
            n = max;
        }
    }
    if(sign === '-'){
        n = Number(numArr.join('')) * -1;
        if(n <= min){
            n = min;
        }
    }
    return n;
};

 

Solutions Code :

var myAtoi = function(s) {
    // 문자열의 양 끝에 있는 공백 제거
    s = s.trim();
    // 빈 문자열인 경우 0 반환
    if (s.length === 0) {
        return 0;
    }
    let num = 0;  // 변환된 정수를 저장할 변수
    let i = 0;    // 문자열의 인덱스
    let sign = 1;  // 부호, 양수는 1, 음수는 -1로 초기화
    // 부호 확인
    if (s[i] === '+') {
        i++;
    } else if (s[i] === '-') {
        i++;
        sign = -1;
    }
    // 숫자 추출
    while (i < s.length && /^\d$/.test(s[i])) {
        // 현재까지의 수를 10배하고 현재 숫자를 더함
        num = num * 10 + parseInt(s[i]);
        i++;
    }
    // 부호 적용 및 정수 오버플로우 체크
    num *= sign;
    num = Math.max(Math.min(num, Math.pow(2, 31) - 1), -Math.pow(2, 31));
    // 최종 변환된 정수 반환
    return num;
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 10. Regular Expression Matching  (0) 2023.10.18
[LeetCode] 9. Palindrome Number  (0) 2023.10.17
[LeetCode] 7. Reverse Integer  (0) 2023.10.16
[LeetCode] 6. Zigzag Conversion  (0) 2023.10.13
[LeetCode] 4. Median of Two Sorted Arrays  (0) 2023.10.11