hwangnk1004 / leetcode_study

0 stars 0 forks source link

8. String to Integer (atoi) #6

Open hwangnk1004 opened 2 years ago

hwangnk1004 commented 2 years ago

8. String to Integer (atoi)

https://leetcode.com/problems/string-to-integer-atoi/

hwangnk1004 commented 2 years ago

다른사람 풀이

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Solution {
    public int myAtoi(String s) {
        while (s.startsWith(" ")) {
            s = s.substring(1);
        }

        int answer = 0;
        Pattern pattern1 = Pattern.compile("^[+-]?[0-9]+");
        Matcher m = pattern1.matcher(s);

        if (m.find()) {
            try {
                answer = Integer.parseInt(m.group());
            } catch (Exception e) {
                if (s.startsWith("-")) {
                    return Integer.MIN_VALUE;
                } else {
                    return Integer.MAX_VALUE;
                }
            }
        }
        return answer;
    }
}
image