프로그래머스 LV1 문자열을 정수로 바꾸기(연습문제)

프로그래머스 LV1 문자열을 정수로 바꾸기(연습문제)

2021, Apr 05    

프로그래머스 lv1 문자열을 정수로 바꾸기(연습문제)

문제 설명

문자열 s를 숫자로 변환한 결과를 반환하는 함수, solution을 완성하세요.

제한 조건

  • s의 길이는 1 이상 5이하입니다.
  • s의 맨앞에는 부호(+, -)가 올 수 있습니다.
  • s는 부호와 숫자로만 이루어져있습니다.
  • s는 “0”으로 시작하지 않습니다.

입출력 예

예를들어 str이 “1234”이면 1234를 반환하고, “-1234”이면 -1234를 반환하면 됩니다.

str은 부호(+,-)와 숫자로만 구성되어 있고, 잘못된 값이 입력되는 경우는 없습니다.


접근

int()함수를 쓰면 간단하게 풀린다.

Docstring:

int([x]) -> integer
int(x, base=10) -> integer

숫자나 문자를 integer로 반환한다. 인자에 아무것도 주어지지 않으면 0을 리턴한다.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base.

The literal can be preceded by ‘+’ or ‘-‘ and be surrounded by whitespace.
문자 앞에는 ‘+’ ‘-‘가 올 수 있고 공백으로 둘러 쌓일수 있다.

int("-123") = -123, int(" 123 ")=123 가능

The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.

int('0b100', base=0)
>>>4

풀이

def solution(s): return int(s)

if __name__ == "__main__":
    s = "-1234" #return "1234"
    print(solution(s))

그냥 int() 쓰면 간단하게 풀릴 문제


출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges